JSON-P 1.1
JSON processing APIs is updated and aligned with Java 8, and provides Stream support for JSON reader.
Let's create an example to demonstrate it.
1
public class Person implements Serializable {
2
3
private String name;
4
private LocalDate birthDate;
5
private List<PhoneNumber> phoneNumbers = new ArrayList<>();
6
7
// setters and getters
8
}
9
10
public class PhoneNumber implements Serializable {
11
12
public static enum Type {
13
HOME, OFFICE;
14
}
15
16
private Type type;
17
private String number;
18
19
// setters and getters
20
}
Copied!
Assume we have a contact list in JSON file, we will read it and convert into Person.
1
[
2
{
3
"name": "Duke",
4
"birthDate": "1995-05-23",
5
"phoneNumbers": [
6
{
7
"number": "100000",
8
"type": "HOME"
9
}, {
10
"number": "200000",
11
"type": "OFFICE"
12
}
13
]
14
},
15
16
{
17
"name": "Hantsy",
18
"birthDate": "1978-01-01",
19
"phoneNumbers": [
20
{
21
"number": "13812345678",
22
"type": "HOME"
23
}
24
]
25
}
26
]
Copied!
Convert JsonArray to Stream via stream method.
1
@Test
2
public void testJsonStream() {
3
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
4
List<String> nameList = reader.readArray().stream()
5
.map(o -> o.asJsonObject().getJsonString("name").getString())
6
.collect(toList());
7
8
assertEquals(Arrays.asList("Duke", "Hantsy"), nameList);
9
10
}
Copied!
JSON-P 1.1 also added JSON Pointer, JSON Patch, JSON Merge Patch support.
An example of using JSON Pointer to query JSON node.
1
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
2
3
JsonArray arrays = reader.readArray();
4
5
JsonPointer p = Json.createPointer("/0/name");
6
JsonValue name = p.getValue(arrays);
7
8
System.out.println("json value ::" + name);
Copied!
An example of using JSON Patch to update some JSON nodes.
1
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
2
JsonArray jsonaArray = reader.readArray();
3
4
JsonPatch patch = Json.createPatchBuilder()
5
.replace("/0/name", "Duke Oracle")
6
.remove("/1")
7
.build();
8
9
JsonArray result = patch.apply(jsonaArray);
10
System.out.println(result.toString());
11
12
Type type = new ArrayList<Person>() {}.getClass().getGenericSuperclass();
13
14
List<Person> person = JsonbBuilder.create().fromJson(result.toString(), type);
15
assertEquals("Duke Oracle", person.get(0).getName());
Copied!
They are very useful to patch the existing entity when add HTTP Patch method support in RESTful APIs, we will demonstrate this later in JAX-RS.
Grab the source codes from my GitHub account, and have a try.
Last modified 8mo ago
Copy link