最近公司有个需求,解析一个json串,是多层不规则的json串,然后要获取超时timeout属性的值进行保存,开始使用String进行处理,但是由于不规则,所以会报错,后来发现了两个jar提供了这个方法。
第一个就是fastjson的JSONPath:
github地址:https://github.com/alibaba/fastjson/wiki/JSONPath
我只用到了其中一个方法:
String s = "{\"id\":1,\"gid\":107,\"title\":\"123\",\"content\":null,\"registrationMark\":\"123\",\"diseaseType\":\"3\",\"zone\":\"I\",\"drugName\":\"123\",\"drugType\":17,\"creater\":null,\"signStatus\":0,\"number\":null,\"expire\":null,\"contractNumber\":null,\"contractExpire\":null,\"createTime\":null,\"updateTime\":null,\"del\":0,\"remarks\":\"`\",\"status\":0,\"gname\":\"南京京拓柯林医药科技有限公司\",\"labels\":[{\"labelId\":9281,\"labelPid\":9280,\"type\":0,\"typeId\":3},{\"labelId\":9291,\"labelPid\":9290,\"type\":0,\"typeId\":3},{\"labelId\":9303,\"labelPid\":9302,\"type\":0,\"typeId\":3}],\"types\":null,\"disease\":null,\"stages\":null,\"gene\":null,\"typeIds\":\"3\"}";
List<String> eval = (List<String>)JSONPath.eval(s, "$..typeId");
System.out.println(JSONPath.read(s, "$..typeId"));
//打印结果是获取所有typeId的值
[3, 3, 3]另外就是JsonPath了:
引入maven:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>String s = "{\"id\":1,\"gid\":107,\"title\":\"123\",\"content\":null,\"registrationMark\":\"123\",\"diseaseType\":\"3\",\"zone\":\"I\",\"drugName\":\"123\",\"drugType\":17,\"creater\":null,\"signStatus\":0,\"number\":null,\"expire\":null,\"contractNumber\":null,\"contractExpire\":null,\"createTime\":null,\"updateTime\":null,\"del\":0,\"remarks\":\"`\",\"status\":0,\"gname\":\"南京京拓柯林医药科技有限公司\",\"labels\":[{\"labelId\":9281,\"labelPid\":9280,\"type\":0,\"typeId\":3},{\"labelId\":9291,\"labelPid\":9290,\"type\":0,\"typeId\":3},{\"labelId\":9303,\"labelPid\":9302,\"type\":0,\"typeId\":3}],\"types\":null,\"disease\":null,\"stages\":null,\"gene\":null,\"typeIds\":\"3\"}";
List<String> authors = JsonPath.read(s, "$..typeId");
//打印结果获取所有typeId的值
[3,3,3]版权声明:本文为zhaochao0037原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。