使用Jackson和JSON Pointer查询解析任何JSON节点
JSON Pointer是字符串表达式,用于标识JSON文档特定节点。RFC 6901规范有定义,用于查询复杂Json文档结构。
1.示例Json文档
{
"firstName": "John",
"lastName": "Doe",
"address": {
"street": "21 2nd Street",
"city": "New York",
"postalCode": "10021-3100",
"coordinates": {
"latitude": 40.7250387,
"longitude": -73.9932568
}
},
"phone": [
"139",
"137"
],
"grade": [
{
"name": "math",
"score": 99
},
{
"name": "english",
"score": 97
}
]
}
该文档包括复杂的嵌套,其中嵌套类型有对象,数组,数组对象。下面使用JSON Pointer进行解析。
2. 解析文档
使用Jackson的核心对象ObjectMapper,首先解析json字符串未JsonNode。
String json = "{\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\": \"Doe\",\n" +
" \"address\": {\n" +
" \"street\": \"21 2nd Street\",\n" +
" \"city\": \"New York\",\n" +
" \"postalCode\": \"10021-3100\",\n" +
" \"coordinates\": {\n" +
" \"latitude\": 40.7250387,\n" +
" \"longitude\": -73.9932568\n" +
" }\n" +
" },\n" +
" \"phone\":[\"139\",\"137\"],\n" +
" \"grade\":[\n" +
" {\"name\":\"math\",\"score\":99},\n" +
" {\"name\":\"english\",\"score\":97}\n" +
" ]\n" +
" }";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
2.1 获取属性
JsonNode firstName = node.at("/firstName");
print("firstName",firstName.toString());
必须以/
开头,表示当前起始节点。
输出结果:
firstName:"John"
2.2 获取对象属性
JsonNode coordinatesNode = node.at("/address/coordinates");
print("coordinatesNode",coordinatesNode.toString());
输出结果:
coordinatesNode:{"latitude":40.7250387,"longitude":-73.9932568}
2.3 获取数组属性
JsonNode phoneNode = node.at("/phone");
print("phoneNode", phoneNode.toString());
输出结果:
phoneNode:["139","137"]
2.4 获取数组属性元素
JsonNode phone1Node = node.at("/phone/0");
print("phone1Node",phone1Node.toString());
输出结果:
phone1Node:"139"
2.4 获取数组对象属性
JsonNode nameNode = node.at("/grade/0/name");
print("name",nameNode.toString());
JsonNode scoreNode = node.at("/grade/0/score");
print("score",scoreNode.toString());
输出结果:
name:"math"
score:99
3. 总结
本文介绍了JSON Pointer是字符串表达式,可以非常方便解析复杂JSON节点值。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/106530134