场景: 之前处理json 对象,常常一层层去判断 ,获取值,
往往涉及到多测判断,特别对于一些比较升的对象,此处推见使用jsonPath
依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <fastjson.version>1.2.24</fastjson.version>
Test:
@Test public void jsonPath() throws Exception{ // { // "username": "zhangsan", // "性别": "男", // "company": { // "companyName": "中华", // "address": "北京" // }, // "cars": [ // "奔驰", // "宝马" // ] // } String json = "{"username":"zhangsan","性别":"男","company":{"companyName":"中华","address":"北京"},"cars":["奔驰","宝马"]}"; JSONObject jsonObject = JSONObject.parseObject(json); //判断 Json中company.companyName 的值是否包含"中华" boolean isContaincompanyName = JSONPath.containsValue(jsonObject,"$.company.companyName","中华"); System.err.println(isContaincompanyName); //获取json中的companyName 的值 Object eval = JSONPath.eval(jsonObject, "$.company.companyName"); System.err.println(eval); /** * 如果该字段没有, 返回null值 */ Object eval1 = JSONPath.eval(jsonObject, "$.company.companyName1"); System.err.println(eval1); }