引言
继《Jackson快速入门》基础篇之后的树模型相关操作。
节点树模型
ObjectMapper构建JsonNode节点树,类似于DOM解析器的XML。
@Test
public void testJsonTree() throws JsonProcessingException, IOException {
String jsonString = "{\"name\":\"Tom\", \"age\":25,\"isTeacher\":false,\"marks\": [100,90,85],\"father\" : {\"name\" : \"Jack\", \"age\" : 45}}";
JsonNode jsonNode = mapper.readTree(jsonString);
System.out.println("----" + jsonNode);
/* 遍历节点名称*/
Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
System.out.println(fieldNames.next());
}
System.out.println("----------------");
/* 遍历节点属性值*/
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
System.out.println(elements.next());
}
System.out.println("----------------");
/* 获取指定节点属性值*/
/* get(int index)for accessing value of the specified element of an array node.
* For other nodes, null is always returned.*/
JsonNode path = jsonNode.get("marks").get(0);
System.out.println(path);
}
输出结果:
树到Json转换
@Test
public void testTree2Json() throws JsonGenerationException, JsonMappingException, IOException {
ArrayNode marksNode = mapper.createArrayNode();
marksNode.add(100);
marksNode.add(90);
marksNode.add(50);
ObjectNode rootNode = mapper.createObjectNode();
rootNode.put("name", "Tom");
rootNode.put("age", 21);
rootNode.set("verified", marksNode);
// 序列化到Tom.json文件中
mapper.writeValue(new File("Tom.json"), rootNode);
// 从文件中再读取回来
JsonNode treeNode = mapper.readTree(new File("Tom.json"));
// 遍历
Iterator<JsonNode> elements = treeNode.elements();
while (elements.hasNext()) {
System.out.println(elements.next());
}
}
输出结果:
树到Java对象转换
通过mapper.treeToValue + Class对象,转换成指定POJO。
@Test
public void testTree2JavaObj() throws JsonGenerationException, JsonMappingException, IOException {
ObjectNode rootNode = mapper.createObjectNode();
ArrayNode marksNode = mapper.createArrayNode();
marksNode.add(100);
marksNode.add(95);
marksNode.add(85);
rootNode.put("name", "Tom");
rootNode.put("age", 21);
rootNode.put("verified", false);
rootNode.set("marks", marksNode);
mapper.writeValue(new File("Tom.json"), rootNode);
JsonNode treeNode = mapper.readTree(new File("Tom.json"));
Student stuTom = mapper.treeToValue(treeNode, Student.class);
System.out.println(stuTom);
}
/**
* 学生类
* <br>类名:Student<br>
*/
static class Student {
String name;
int age;
boolean verified;
int[] marks;
// getter-setter
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", verified=" + verified + ", marks="
+ Arrays.toString(marks) + "]";
}
}
输出结果:
综上就是关于使用jackson操作节点树的相关用法,包括遍历各种元素,选取各种元素,以及树与json、POJO之间的转换。