使用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節點值。