JSON-B 1.0
JSON-P provides the lower JSON node operations, JSON Binding API provides advanced operations on serialization of Java objects to JSON string and de-serialization of JSON string to Java objects.

Serialization

An example to serialize a Java object to JSON string.
1
Person duke = new Person("Duke", LocalDate.of(1995, 5, 23));
2
duke.setPhoneNumbers(
3
Arrays.asList(
4
new PhoneNumber(HOME, "100000"),
5
new PhoneNumber(OFFICE, "200000")
6
)
7
);
8
9
Jsonb jsonMapper = JsonbBuilder.create();
10
String json = jsonMapper.toJson(duke);
11
12
LOG.log(Level.INFO, "converted json result: {0}", json);
Copied!
JsonPath allow you read the values of JSON nodes.
1
String name = JsonPath.parse(json).read("$.name");
2
assertEquals("Duke", name);
Copied!
JsonPath.using() method accepts custom configuration APIs to configure the json provider, eg. using Gson instead of the default JSON provider.
1
Configuration config = Configuration.defaultConfiguration()
2
.jsonProvider(new GsonJsonProvider())
3
.mappingProvider(new GsonMappingProvider());
4
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {
5
};
6
7
List<String> numbers = JsonPath.using(config).parse(json).read("$.phoneNumbers[*].number", typeRef);
8
9
assertEquals(Arrays.asList("100000", "200000"), numbers);
Copied!

Deserialization

Read the JSON string and map to an object directly.
1
Jsonb jsonMapper = JsonbBuilder.create();
2
3
Person person = jsonMapper.fromJson(JsonbTest.class.getResourceAsStream("/person.json"), Person.class);
4
5
assertEquals("Duke", person.getName());
6
7
Type type = new ArrayList<Person>() {}
8
.getClass()
9
.getGenericSuperclass();
10
11
List<Person> persons = jsonMapper.fromJson(JsonbTest.class.getResourceAsStream("/persons.json"), type);
12
13
assertTrue(persons.size() == 2);
Copied!

JSON-B annotations

JSON-B provides a series of annotations to adjust the serialization and deserialization for an object, including @JsonbProperty, @JsonbPropertyOrder, @JsonbTransient etc.
1
@JsonbProperty
2
private String name;
Copied!
Grab the source codes from my GitHub account, and have a try.
Last modified 8mo ago