五JSONPath使用(Java)
1. 开发环境JDK 1.8 SpringBoot 2.1.18 2. 添加依赖 com.jayway.jsonpath json-path 2.6.0 3. 读取JSONString jsonStr = "{"name":"大润发超市",fruits: [{"name":"苹果"}, {"name":"香蕉"}]}"; JSONObject jsonObject = JSONObject.parseObject(jsonStr); DocumentContext dc = JsonPath.parse(jsonStr); List 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. 写入JSONString jsonStr = "{"name":"大润发超市",fruits: [{"name":"苹果"}, {"name":"香蕉"}]}"; JSONObject jsonObject = JSONObject.parseObject(jsonStr); DocumentContext dc = JsonPath.parse(jsonStr); dc.set("$.name", "华润苏果超时"); dc.set("$.fruits[1].name", "葡萄"); List 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