JsonPath使用说明
依赖包:
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.4.0</version> </dependency>
代码:
package json.jsonpath; import com.google.gson.JsonObject; import com.jayway.jsonpath.JsonPath; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.List; /** * 测试Jsonpath * 作用:通过路径获取Json字段值 */ public class MyJsonPath { public static void main(String[] args) throws IOException { String json = FileUtils.readFileToString(new File("src/main/resource/json/jq.json"), "utf8"); System.out.println("Json:" + json); /** * 根据路径获取值 * */ String bjnr = JsonPath.read(json, "$.data.bjnr"); System.out.println("报警内容:" + bjnr); String isInvolved = JsonPath.read(json, "$.data.isInvolved"); System.out.println("报警人是否是涉案人:" + isInvolved); /** * 可以提前编辑一个路径,并多次使用它 * */ JsonPath path = JsonPath.compile("$.data.keywords"); System.out.println("keywords:" + path.read(json)); /** * 获取JSON中的对象数组 * */ List<JsonObject> hwList = JsonPath.read(json, "$.data.hwList"); System.out.println("hwList:" + hwList); /** * 获取JSON中的所有id的值 * */ List<String> ids = JsonPath.read(json, "$..id"); System.out.println("ids:" + ids); } }
测试结果:
报警内容:报警人称发现一名小偷(男性,30岁左右,1米63,棕色外套,红色毛衣)往好利达超市方向逃跑。 报警人是否是涉案人:2 keywords:人称发现,发现小偷,方向逃跑 hwList:[{"id":24,"highFWords":"报警","count":46266,"pos":null,"section":"10000以上"},{"id":26,"highFWords":"人称","count":17806,"pos":null,"section":"10000以上"}] ids:[24,26]
json:
{ "code": 200, "message": "查询成功", "data": { "jjdbh": "3323422", "danger": "", "keywords": "人称发现,发现小偷,方向逃跑", "verb": "发现,逃跑", "noun": "报警,人称,小偷,男性,棕色,外套,毛衣,利达,超市,方向", "adv": "往好","bjnr": "报警人称发现一名小偷(男性,30岁左右,1米63,棕色外套,红色毛衣)往好利达超市方向逃跑。", "fxwp": "2","hwList": [ { "id": 24, "highFWords": "报警", "count": 46266, "pos": null, "section": "10000以上" }, { "id": 26, "highFWords": "人称", "count": 17806, "pos": null, "section": "10000以上" } ], "isInvolved": "2" } }