javax.json.bind.Jsonb类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(9.1k)|赞(0)|评价(0)|浏览(274)

本文整理了Java中javax.json.bind.Jsonb类的一些代码示例,展示了Jsonb类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Jsonb类的具体详情如下:
包路径:javax.json.bind.Jsonb
类名称:Jsonb

Jsonb介绍

[英]Jsonb provides an abstraction over the JSON Binding framework operations:

  • fromJson: read JSON input, deserialize to Java objects content tree
  • toJson: serialize Java objects content tree to JSON input

Instance of this class is created using javax.json.bind.JsonbBuilderbuilder methods:

// Example 1 - Creating Jsonb using default JsonbBuilder instance provided by default JsonbProvider

Deserializing (reading) JSON
Can de-serialize JSON data that represents either an entire JSON document or a subtree of a JSON document. Reading (deserializing) object content tree from a File:

Jsonb jsonb = JsonbBuilder.create(); 
Book book = jsonb.fromJson(new FileReader("jsonfile.json"), Book.class);

If the deserialization process is unable to deserialize the JSON content to an object content tree, fatal error is reported that terminates processing by throwing JsonbException.

Serializing (writing) to JSON

Serialization writes the representation of a Java object content tree into JSON data. Writing (serializing) object content tree to a File:

jsonb.toJson(object, new FileWriter("foo.json"));

Writing (serializing) to a Writer:

jsonb.toJson(object, new PrintWriter(System.out));

Encoding

In deserialization operations ( fromJson), encoding of JSON data is detected automatically. Use the javax.json.bind.JsonbConfig API to configure expected input encoding used within deserialization operations. Client applications are expected to supply a valid character encoding as defined in the RFC 7159 and supported by Java Platform. In serialization operations ( toJson), UTF-8 encoding is used by default for writing JSON data. Use the javax.json.bind.JsonbConfig API to configure the output encoding used within serialization operations. Client applications are expected to supply a valid character encoding as defined in the RFC 7159 and supported by Java Platform.

For optimal use, JsonbBuilder and Jsonb instances should be reused - for a typical use-case, only one Jsonb instance is required by an application.

All the methods in this class are safe for use by multiple concurrent threads.

Calling Closable.close() method will cleanup all CDI managed components (such as adapters with CDI dependencies) created during interaction with Jsonb. Calling close() must be done after all threads has finished interaction with Jsonb. If there are remaining threads working with Jsonb and close() is called, behaviour is undefined.
[中]Jsonb提供了对JSON绑定框架操作的抽象:
*fromJson:读取JSON输入,反序列化到Java对象内容树
*toJson:将Java对象内容树序列化为JSON输入
这个类的实例是使用javax创建的。json。绑定JsonbBuilderbuilder方法:
<0$>>反序列化(读取)JSON
可以反序列化表示整个JSON文档或JSON文档子树的JSON数据。从文件读取(反序列化)对象内容树:

Jsonb jsonb = JsonbBuilder.create(); 
Book book = jsonb.fromJson(new FileReader("jsonfile.json"), Book.class);

如果反序列化进程无法将JSON内容反序列化到对象内容树,则会报告致命错误,通过抛出JSONBEException终止处理。
序列化(写入)到JSON
序列化将Java对象内容树的表示写入JSON数据。将对象内容树写入(序列化)文件:

jsonb.toJson(object, new FileWriter("foo.json"));

向写入程序写入(序列化):

jsonb.toJson(object, new PrintWriter(System.out));

编码
在反序列化操作(fromJson)中,会自动检测JSON数据的编码。使用javax。json。绑定用于配置反序列化操作中使用的预期输入编码的JsonbConfig API。客户机应用程序应提供RFC 7159中定义的、Java平台支持的有效字符编码。在序列化操作(toJson)中,默认情况下,UTF-8编码用于写入JSON数据。使用javax。json。绑定用于配置序列化操作中使用的输出编码的JsonbConfig API。客户机应用程序应提供RFC 7159中定义的、Java平台支持的有效字符编码。
为了获得最佳使用,应该重用JsonbBuilder和Jsonb实例——对于典型用例,应用程序只需要一个Jsonb实例。
此类中的所有方法对于多个并发线程都是安全的。
呼叫Closable。close()方法将清理在与Jsonb交互期间创建的所有CDI托管组件(例如具有CDI依赖项的适配器)。调用close()必须在所有线程完成与Jsonb的交互后完成。如果有剩余的线程使用Jsonb,并且调用了close(),则行为是未定义的。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
protected Object readInternal(Type resolvedType, Reader reader) throws Exception {
  return getJsonb().fromJson(reader, resolvedType);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected void writeInternal(Object o, @Nullable Type type, Writer writer) throws Exception {
  if (type instanceof ParameterizedType) {
    getJsonb().toJson(o, type, writer);
  }
  else {
    getJsonb().toJson(o, writer);
  }
}

代码示例来源:origin: org.talend.sdk.component/component-server-proxy

public <T> Map<String, Object> toJsonMap(final T model) {
    return (Map<String, Object>) jsonb.fromJson(jsonb.toJson(model), Map.class);
  }
}

代码示例来源:origin: org.apache.johnzon/johnzon-jsonb

@Override
  public void close() throws Exception {
    instance.close();
  }
}

代码示例来源:origin: org.jnosql.diana/couchbase-driver

static JsonObject toJson(Jsonb jsonb, Object value) {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    jsonb.toJson(value, stream);
    InputStream inputStream = new ByteArrayInputStream(stream.toByteArray());
    Map<String, ?> map = jsonb.fromJson(inputStream, TYPE);

    return JsonObject.from(map);

  }
}

代码示例来源:origin: org.talend.sdk.component/component-form-core

@Override
  public void close() throws Exception {
    if (closeJsonb) {
      jsonb.close();
    }
  }
}

代码示例来源:origin: org.springframework/spring-web

@Override
protected Object readInternal(Type resolvedType, Reader reader) throws Exception {
  return getJsonb().fromJson(reader, resolvedType);
}

代码示例来源:origin: org.springframework/spring-web

@Override
protected void writeInternal(Object o, @Nullable Type type, Writer writer) throws Exception {
  if (type instanceof ParameterizedType) {
    getJsonb().toJson(o, type, writer);
  }
  else {
    getJsonb().toJson(o, writer);
  }
}

代码示例来源:origin: org.talend.sdk.component/component-runtime-impl

public <T> Record toRecord(final T data, final Supplier<Jsonb> jsonbProvider,
    final Supplier<RecordBuilderFactory> recordBuilderProvider) {
  if (Record.class.isInstance(data)) {
    return Record.class.cast(data);
  }
  if (JsonObject.class.isInstance(data)) {
    return json2Record(recordBuilderProvider.get(), JsonObject.class.cast(data));
  }
  final Jsonb jsonb = jsonbProvider.get();
  return json2Record(recordBuilderProvider.get(), jsonb.fromJson(jsonb.toJson(data), JsonObject.class));
}

代码示例来源:origin: org.apache.geronimo/geronimo-opentracing-common

public void destroy() {
  try {
    jsonb.close();
  } catch (final Exception e) {
    // no-op
  }
}

代码示例来源:origin: jersey/jersey

@Override
public Object readFrom(Class<Object> type, Type genericType,
            Annotation[] annotations,
            MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders,
            InputStream entityStream) throws IOException, WebApplicationException {
  Jsonb jsonb = getJsonb(type);
  try {
    return jsonb.fromJson(entityStream, genericType);
  } catch (JsonbException e) {
    throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e);
  }
}

代码示例来源:origin: jersey/jersey

@Override
public void writeTo(Object o, Class<?> type, Type genericType,
          Annotation[] annotations,
          MediaType mediaType,
          MultivaluedMap<String, Object> httpHeaders,
          OutputStream entityStream) throws IOException, WebApplicationException {
  Jsonb jsonb = getJsonb(type);
  try {
    entityStream.write(jsonb.toJson(o).getBytes(AbstractMessageReaderWriterProvider.getCharset(mediaType)));
    entityStream.flush();
  } catch (IOException e) {
    throw new ProcessingException(LocalizationMessages.ERROR_JSONB_SERIALIZATION(), e);
  }
}

代码示例来源:origin: org.talend.sdk.component/component-runtime-impl

public Object toType(final Object data, final Class<?> parameterType,
    final Supplier<JsonBuilderFactory> factorySupplier, final Supplier<JsonProvider> providerSupplier,
    final Supplier<Jsonb> jsonbProvider) {
  if (parameterType.isInstance(data)) {
    return data;
  }
  final Jsonb jsonb = jsonbProvider.get();
  final String inputAsJson;
  if (JsonObject.class.isInstance(data)) {
    if (JsonObject.class == parameterType) {
      return data;
    }
    inputAsJson = JsonObject.class.cast(data).toString();
  } else if (Record.class.isInstance(data)) {
    final JsonObject asJson = toJson(factorySupplier, providerSupplier, Record.class.cast(data));
    if (JsonObject.class == parameterType) {
      return asJson;
    }
    inputAsJson = asJson.toString();
  } else {
    inputAsJson = jsonb.toJson(data);
  }
  if (parameterType == JsonObject.class) {
    return jsonb.fromJson(inputAsJson, parameterType);
  }
  return jsonb.fromJson(inputAsJson, parameterType);
}

代码示例来源:origin: apache/johnzon

@Override
  public void close() throws Exception {
    instance.close();
  }
}

代码示例来源:origin: jooby-project/jooby

@Override
public Object parse(final TypeLiteral<?> type, final Context ctx) throws Throwable {
 MediaType ctype = ctx.type();
 if (ctype.isAny()) {
  // */*
  return ctx.next();
 }
 if (ctype.matches(this.type)) {
  return ctx
    .ifbody(body -> jsonb.fromJson(body.text(), type.getType()))
    .ifparam(values -> jsonb.fromJson(values.first(), type.getType()));
 }
 return ctx.next();
}

代码示例来源:origin: jooby-project/jooby

@Override
public void render(final Object object, final Context ctx) throws Exception {
 if (ctx.accepts(this.type)) {
  ctx.type(this.type)
    .send(jsonb.toJson(object));
 }
}

代码示例来源:origin: org.apache.tomee/mp-jwt

jsonValue = jsonb.fromJson(jsonb.toJson(value), JsonObject.class);

代码示例来源:origin: org.talend.sdk.component/component-server

@PreDestroy
private void destroy() {
  try {
    defaultMapper.close();
  } catch (final Exception e) {
    log.error(e.getMessage(), e);
  }
}

代码示例来源:origin: resteasy/Resteasy

@Override
public Object readFrom(Class<Object> type, Type genericType,
               Annotation[] annotations, MediaType mediaType,
               MultivaluedMap<String, String> httpHeaders,
               InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException {
 Jsonb jsonb = getJsonb(type);
 final EmptyCheckInputStream is = new EmptyCheckInputStream(entityStream);
 try {
   return jsonb.fromJson(is, genericType);
   // If null is returned, considered to be empty stream
 } catch (Throwable e)
 {
   if (is.isEmpty()) {
    return null;
   }
   // detail text provided in logger message
   throw new ProcessingException(Messages.MESSAGES.jsonBDeserializationError(e, e.getMessage()), e);
 }
}

代码示例来源:origin: resteasy/Resteasy

@Override
public String[] getMessages() {
 try {
   return new String[]{mapper.toJson(messageList)};
 } catch (Exception e) {
   throw new RuntimeException(e);
 }
}

相关文章