jsonpath的简单用法(转)

转自:

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)));

 

posted @ 2021-11-08 16:23  Mars.wang  阅读(1020)  评论(0编辑  收藏  举报