fastjson.JSONPath使用举例
源码:
/** * 根据路径获取值 * */ String bjnr = (String) JSONPath.read(json, "$.data.bjnr"); System.out.println("报警内容:" + bjnr); String isInvolved = (String) JSONPath.read(json, "$.data.isInvolved"); System.out.println("报警人是否是涉案人:" + isInvolved); /** * 获取JSON中的对象数组 * */ List<JSONObject> hwList = (List<JSONObject>) JSONPath.read(json, "$.data.hwList"); System.out.println("hwList:" + hwList); /** * 获取JSON中的所有id的值 * */ List<String> ids = (List<String>) JSONPath.read(json, "$..id"); System.out.println("ids:" + ids); /** * 可以提前编辑一个路径,并多次使用它 * */ JSONPath path = JSONPath.compile("$.data.keywords"); System.out.println("keywords:" + path.eval(JSON.parseObject(json)));
运行结果:
报警内容:报警人称发现一名小偷(男性,30岁左右,1米63,棕色外套,红色毛衣)往好利达超市方向逃跑。
报警人是否是涉案人:2
hwList:[{"count":46266,"section":"10000以上","id":24,"highFWords":"报警"},{"count":17806,"section":"10000以上","id":26,"highFWords":"人称"}]
ids:[24, 26]
keywords:人称发现,发现小偷,方向逃跑
测试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"
}
}
end