转自:

https://www.cnblogs.com/gongxr/p/14251995.html

jsonpath就是json版的xmlPath,提供了类似xPath类似的方式来操作json,非常方便

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;


public class Test2 {


    public static void main(String[] args) {
        String json = "{\"objs\" : [{\"obj\" : 1411455611975}]}";
        DocumentContext ext = JsonPath.parse(json);
        JsonPath p = JsonPath.compile("$.objs[0].obj");
        ext.set(p, 141145561197333L);
        String author = ext.jsonString();
        System.err.println(author);

    }
}

 

/**
         * 根据路径获取值
         * */
        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)));

 

相关文章:

  • 2021-12-06
  • 2022-12-23
  • 2021-07-24
  • 2022-02-03
  • 2022-12-23
  • 2021-08-14
  • 2021-12-02
猜你喜欢
  • 2021-04-15
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2021-08-12
相关资源
相似解决方案