龙空技术网

五、JSONPath使用(Java)

可靠80后程序猿 222

前言:

此时朋友们对“jsonpath在线解析”大致比较关注,大家都需要知道一些“jsonpath在线解析”的相关知识。那么小编在网上搜集了一些有关“jsonpath在线解析””的相关文章,希望姐妹们能喜欢,大家一起来了解一下吧!

1. 开发环境JDK 1.8SpringBoot 2.1.182. 添加依赖

<dependency>    <groupId>com.jayway.jsonpath</groupId>    <artifactId>json-path</artifactId>    <version>2.6.0</version></dependency>
3. 读取JSON
String jsonStr = "{\"name\":\"大润发超市\",fruits: [{\"name\":\"苹果\"}, {\"name\":\"香蕉\"}]}";JSONObject jsonObject = JSONObject.parseObject(jsonStr);DocumentContext dc = JsonPath.parse(jsonStr);List<String> jsonPaths = JsonHelperUtils.getJsonPath(jsonObject);for(String jsonPath : jsonPaths) {    Object actual = dc.read("$." + jsonPath);    System.out.println("$." + jsonPath + " = " + actual);}

输出结果如下:

10:02:01.133 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['name']$.name = 大润发超市10:02:01.146 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['fruits'][0]['name']$.fruits[0].name = 苹果10:02:01.147 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['fruits'][1]['name']$.fruits[1].name = 香蕉
4. 写入JSON
String jsonStr = "{\"name\":\"大润发超市\",fruits: [{\"name\":\"苹果\"}, {\"name\":\"香蕉\"}]}";JSONObject jsonObject = JSONObject.parseObject(jsonStr);DocumentContext dc = JsonPath.parse(jsonStr);dc.set("$.name", "华润苏果超时");dc.set("$.fruits[1].name", "葡萄");List<String> jsonPaths = JsonHelperUtils.getJsonPath(jsonObject);for(String jsonPath : jsonPaths) {    Object actual = dc.read("$." + jsonPath);    System.out.println("$." + jsonPath + " = " + actual);}

输出结果如下:

10:05:50.665 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['name']10:05:50.682 [main] DEBUG com.jayway.jsonpath.internal.JsonContext - Set path $['name'] new value 华润苏果超时10:05:50.684 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['fruits'][1]['name']10:05:50.685 [main] DEBUG com.jayway.jsonpath.internal.JsonContext - Set path $['fruits'][1]['name'] new value 葡萄10:05:50.745 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['name']$.name = 华润苏果超时10:05:50.746 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['fruits'][0]['name']$.fruits[0].name = 苹果10:05:50.746 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['fruits'][1]['name']$.fruits[1].name = 葡萄

注意:在读取json时,需要通过异常来判断读取的是集合还是对象,参考如下示例:

String jsonStr = "";String expression = "";try {    //Will throw an java.lang.ClassCastException    List<Object> values = JsonPath.parse(jsonStr).read(expression);    for(Object actual : values) {        Object actual = JsonPath.parse(jsonStr).read(expression);    }}catch(ClassCastException e1) {    Object actual = JsonPath.parse(jsonStr).read(expression);}

标签: #jsonpath在线解析