常見需求
1、讀取字符串中某個key的值,但是這個key的層級比較深
2、篩選出json字符串中符合條件的葉子節(jié)點
3、讀取某個key在json字符串中所有的值
4、替換json字符串中的某個key的值
5、移除json字符串中某個key
常用方法
1、map
2、map
3、map
4、set /put?
? ? ? 其中set方法只能在xpath存在的情況下執(zhí)行更新,put方法若指定的xpath 的key不存在,則添加,若存在,則執(zhí)行更新操作
5、delete
使用示例
public static void main(String[] args) {
String jsonStr ="{\n" +
"? ? \"store\": {\n" +
"? ? ? ? \"book\": [\n" +
"? ? ? ? ? ? {\n" +
"? ? ? ? ? ? ? ? \"category\": \"reference\",\n" +
"? ? ? ? ? ? ? ? \"author\": \"hhhhh\",\n" +
"? ? ? ? ? ? ? ? \"title\": \"Sayings of the Century\",\n" +
"? ? ? ? ? ? ? ? \"price\": 8.95\n" +
"? ? ? ? ? ? }\n" +
"? ? ? ? ],\n" +
"? ? ? ? \"bicycle\": {\n" +
"? ? ? ? ? ? \"color\": \"red\",\n" +
"? ? ? ? ? ? \"price\": 19.95\n" +
"? ? ? ? }\n" +
"? ? },\n" +
"? ? \"expensive\": 10\n" +
"}";
DocumentContext json = JsonPath.parse(jsonStr);
String setMethodPath ="$..book[0].author";
String tagValue ="ReplacedText";
String putMethodPath ="$..book[0]";
String newValue ="hahahha";
String deleteMethodPath ="$.expensive";
System.out.println(json.set(setMethodPath, tagValue).jsonString());
System.out.println(json.put(putMethodPath,"newKey", newValue).jsonString());
System.out.println(json.put(putMethodPath,"author","updateValue").jsonString());
System.out.println(json.delete(deleteMethodPath).jsonString());
}
依賴包
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>minidev-parent</artifactId>
<version>2.3</version>
</dependency>
參考
https://github.com/jayway/JsonPath
文檔
http://static.javadoc.io/com.jayway.jsonpath/json-path/2.2.0/com/jayway/jsonpath/WriteContext.html