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.
public class Person implements Serializable {
private String name;
private LocalDate birthDate;
private List<PhoneNumber> phoneNumbers = new ArrayList<>();
// setters and getters
}
public class PhoneNumber implements Serializable {
public static enum Type {
HOME, OFFICE;
}
private Type type;
private String number;
// setters and getters
}
Person
.[
{
"name": "Duke",
"birthDate": "1995-05-23",
"phoneNumbers": [
{
"number": "100000",
"type": "HOME"
}, {
"number": "200000",
"type": "OFFICE"
}
]
},
{
"name": "Hantsy",
"birthDate": "1978-01-01",
"phoneNumbers": [
{
"number": "13812345678",
"type": "HOME"
}
]
}
]
JsonArray
to Stream
via stream
method.@Test
public void testJsonStream() {
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
List<String> nameList = reader.readArray().stream()
.map(o -> o.asJsonObject().getJsonString("name").getString())
.collect(toList());
assertEquals(Arrays.asList("Duke", "Hantsy"), nameList);
}
An example of using JSON Pointer to query json node.
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
JsonArray arrays = reader.readArray();
JsonPointer p = Json.createPointer("/0/name");
JsonValue name = p.getValue(arrays);
System.out.println("json value ::" + name);
JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
JsonArray jsonaArray = reader.readArray();
JsonPatch patch = Json.createPatchBuilder()
.replace("/0/name", "Duke Oracle")
.remove("/1")
.build();
JsonArray result = patch.apply(jsonaArray);
System.out.println(result.toString());
Type type = new ArrayList<Person>() {}.getClass().getGenericSuperclass();
List<Person> person = JsonbBuilder.create().fromJson(result.toString(), type);
assertEquals("Duke Oracle", person.get(0).getName());
Grab the source codes from my github account, and have a try.
评论