1. Overview
1.概述
For a long time, there was no standard for JSON processing in Java. The most common libraries used for JSON processing are Jackson and Gson.
在很长一段时间里,Java中没有JSON处理的标准。最常见的用于JSON处理的库是Jackson和Gson。
Recently, Java EE7 came with an API for parsing and generating JSON (JSR 353: Java API for JSON Processing).
最近,Java EE7提供了一个用于解析和生成JSON的API(JSR 353: Java API for JSON Processing)。
And finally, with the release of JEE 8, there is a standardized API (JSR 367: Java API for JSON Binding (JSON-B)).
最后,随着JEE 8的发布,出现了一个标准化的API(JSR 367:Java API for JSON Binding(JSON-B))。
For now, its main implementations are Eclipse Yasson (RI) and Apache Johnzon.
目前,它的主要实现是Eclipse Yasson(RI)和Apache Johnzon。
2. JSON-B API
2.JSON-B API
2.1. Maven Dependency
2.1.Maven的依赖性
Let’s start by adding the necessary dependency.
让我们从添加必要的依赖关系开始。
Keep in mind that in many cases it’ll be enough to include the dependency for the chosen implementation and the javax.json.bind-api will be included transitively:
请记住,在很多情况下,只需要包含所选择的实现的依赖关系,javax.json.bind-api将被过渡性地包含。
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
</dependency>
The most recent version can be found at Maven Central.
最新的版本可以在Maven Central找到。
3. Using Eclipse Yasson
3.使用Eclipse Yasson[/strong
Eclipse Yasson is the official reference implementation of JSON Binding API (JSR-367).
Eclipse Yasson是JSON Binding API(JSR-367)的官方参考实现。
3.1. Maven Dependency
3.1.Maven的依赖性
To use it, we need to include the following dependencies in our Maven project:
要使用它,我们需要在Maven项目中包含以下依赖项。
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
The most recent versions can be found at Maven Central.
最新的版本可以在Maven Central.找到。
4. Using Apache Johnzon
4.使用Apache Johnzon
Another implementation we can use is Apache Johnzon which complies with the JSON-P (JSR-353) and JSON-B (JSR-367) APIs.
我们可以使用的另一个实现是Apache Johnzon,它符合JSON-P(JSR-353)和JSON-B(JSR-367)API。
4.1. Maven Dependency
4.1.Maven的依赖性
To use it, we need to include the following dependencies in our Maven project:
要使用它,我们需要在Maven项目中包含以下依赖项。
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-json_1.1_spec</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-jsonb</artifactId>
<version>1.1.4</version>
</dependency>
The most recent versions can be found at Maven Central.
最新的版本可以在Maven Central.找到。
5. API Features
5.API特点
The API provides annotations for customizing serialization/deserialization.
该API提供了用于定制序列化/反序列化的注解。
Let’s create a simple class and see how the example configuration looks like:
让我们创建一个简单的类,看看这个例子的配置是什么样子的。
public class Person {
private int id;
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
private String email;
@JsonbTransient
private int age;
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate registeredDate;
private BigDecimal salary;
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
// standard getters and setters
}
After serialization, an object of this class will look like:
在序列化之后,这个类的对象将看起来像。
{
"email":"jhon@test.com",
"id":1,
"person-name":"Jhon",
"registeredDate":"07-09-2019",
"salary":"1000.0"
}
The annotations used here are:
这里使用的注释是。
- @JsonbProperty – which is used for specifying a custom field name
- @JsonbTransient – when we want to ignore the field during deserialization/serialization
- @JsonbDateFormat – when we want to define the display format of the date
- @JsonbNumberFormat – for specifying the display format for numeric values
- @JsonbNillable – for enabling serialization of null values
5.1. Serialization and Deserialization
5.1.序列化和反序列化
First of all, to obtain the JSON representation of our object, we need to use the JsonbBuilder class and its toJson() method.
首先,为了获得我们对象的JSON表示,我们需要使用JsonbBuilder类和其toJson()方法。
To start, let’s create a simple Person object like this:
首先,让我们创建一个简单的Person对象,像这样。
Person person = new Person(
1,
"Jhon",
"jhon@test.com",
20,
LocalDate.of(2019, 9, 7),
BigDecimal.valueOf(1000));
And, instantiate the Jsonb class:
并且,实例化Jsonb类。
Jsonb jsonb = JsonbBuilder.create();
Then, we use the toJson method:
然后,我们使用toJson方法。
String jsonPerson = jsonb.toJson(person);
To obtain the following JSON representation:
为了获得以下JSON表示。
{
"email":"jhon@test.com",
"id":1,
"person-name":"Jhon",
"registeredDate":"07-09-2019",
"salary":"1000.0"
}
If we want to do the conversion the other way, we can use the fromJson method:
如果我们想以其他方式进行转换,我们可以使用fromJson方法。
Person person = jsonb.fromJson(jsonPerson, Person.class);
Naturally, we can also process collections:
当然,我们也可以处理收款。
List<Person> personList = Arrays.asList(...);
String jsonArrayPerson = jsonb.toJson(personList);
To obtain the following JSON representation:
为了获得以下JSON表示。
[
{
"email":"jhon@test.com",
"id":1,
"person-name":"Jhon",
"registeredDate":"09-09-2019",
"salary":"1000.0"
},
{
"email":"jhon1@test.com",
"id":2,
"person-name":"Jhon",
"registeredDate":"09-09-2019",
"salary":"1500.0"
},
...
]
To convert from JSON array to List we’ll use the fromJson API:
为了从JSON数组转换为List,我们将使用fromJson API。
List<Person> personList = jsonb.fromJson(
personJsonArray,
new ArrayList<Person>(){}.getClass().getGenericSuperclass()
);
5.2. Custom Mapping With JsonbConfig
5.2.使用JsonbConfig的自定义映射
The JsonbConfig class allows us to customize the mapping process for all classes.
JsonbConfig类允许我们定制所有类的映射过程。
For example, we can change the default naming strategies or the properties order.
例如,我们可以改变默认的命名策略或属性顺序。
Now, we’ll use the LOWER_CASE_WITH_UNDERSCORES strategy:
现在,我们将使用LOWER_CASE_WITH_UNDERSCORES策略。
JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(
PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
Jsonb jsonb = JsonbBuilder.create(config);
String jsonPerson = jsonb.toJson(person);
To obtain the following JSON representation:
为了获得以下JSON表示。
{
"email":"jhon@test.com",
"id":1,
"person-name":"Jhon",
"registered_date":"07-09-2019",
"salary":"1000.0"
}
Now, we’ll change the property order with the REVERSE strategy. Using this strategy, the order of properties is in reverse order to lexicographical order.
This can also be configured at compile time with the annotation @JsonbPropertyOrder. Let’s see it in action:
现在,我们将用REVERSE策略改变属性顺序。使用这个策略,属性的顺序与lexicographical顺序相反。
这也可以在编译时用注解@JsonbPropertyOrder.配置。让我们看看它的实际效果。
JsonbConfig config
= new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE);
Jsonb jsonb = JsonbBuilder.create(config);
String jsonPerson = jsonb.toJson(person);
To obtain the following JSON representation:
为了获得以下JSON表示。
{
"salary":"1000.0",
"registeredDate":"07-09-2019",
"person-name":"Jhon",
"id":1,
"email":"jhon@test.com"
}
5.3. Custom Mapping With Adapters
5.3.使用适配器的自定义映射
When the annotations and the JsonbConfig class aren’t enough for us, we can use adapters.
当注解和JsonbConfig类对我们来说还不够,我们可以使用适配器。
To use them, we’ll need to implement the JsonbAdapter interface, which defines the following methods:
为了使用它们,我们需要实现JsonbAdapter接口,它定义了以下方法。
- adaptToJson – With this method, we can use custom conversion logic for the serialization process.
- adaptFromJson – This method allows us to use custom conversion logic for the deserialization process.
Let’s create a PersonAdapter to process the id and name attributes of the Person class:
让我们创建一个PersonAdapter来处理Person类的id和name属性。
public class PersonAdapter implements JsonbAdapter<Person, JsonObject> {
@Override
public JsonObject adaptToJson(Person p) throws Exception {
return Json.createObjectBuilder()
.add("id", p.getId())
.add("name", p.getName())
.build();
}
@Override
public Person adaptFromJson(JsonObject adapted) throws Exception {
Person person = new Person();
person.setId(adapted.getInt("id"));
person.setName(adapted.getString("name"));
return person;
}
}
Furthermore, we’ll assign the adapter to our JsonbConfig instance:
此外,我们将把适配器分配给我们的JsonbConfig实例。
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
And we’ll get the following JSON representation:
我们将得到以下JSON表示。
{
"id":1,
"name":"Jhon"
}
6. Conclusion
6.结论
In this tutorial, we saw an example of how to integrate the JSON-B API with Java applications using the available implementations, along with examples of customizing serialization and deserialization at both compile and runtime.
在本教程中,我们看到了一个如何使用现有的实现将JSON-B API与Java应用程序集成的例子,以及在编译和运行时定制序列化和反序列化的例子。
The complete code is available, as always, over on Github.
完整的代码可一如既往地在Github上获取。