常见需求
1、读取字符串中某个key的值,但是这个key的层级比较深
2、筛选出json字符串中符合条件的叶子节点
3、读取某个key在json字符串中所有的值
4、替换json字符串中的某个key的值
5、移除json字符串中某个key
常用方法
1、map
2、map
3、map
4、set /put
其中set方法只能在xpath存在的情况下执行更新,put方法若指定的xpath 的key不存在,则添加,若存在,则执行更新操作
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());
}
依赖包
参考
https://github.com/jayway/JsonPath
文档
http://static.javadoc.io/com.jayway.jsonpath/json-path/2.2.0/com/jayway/jsonpath/WriteContext.html