json.parse java_MySQL的jar包下载

Java (1) 2024-09-29 19:23

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
json.parse java_MySQL的jar包下载,希望能够帮助你!!!。

1. 开发环境

  • JDK 1.8
  • SpringBoot 2.1.18

2. 添加依赖

<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); }

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

下一篇

已是最新文章

发表回复