JsonPath的使用

官方:https://github.com/json-path/JsonPath

引入包

    <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <version>2.2.0</version>
    </dependency>
package demo.json;

/**
 * https://blog.csdn.net/lwg_1540652358/article/details/84111339
 * <p>
 * JsonPath中的"根成员对象"始终称为$,无论是对象还是数组
 * JsonPath表达式可以使用点表示法
 * $.store.book[0].title
 * 或括号表示法
 * $['store']['book'][0]['title']
 */

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ReadContext;
import net.minidev.json.JSONArray;

import java.util.List;
import java.util.Map;

/**
 * 过滤器是用于筛选数组的逻辑表达式。一个典型的过滤器将是[?(@.age > 18)],其中@表示正在处理的当前项目。
 * 可以使用逻辑运算符&&和||创建更复杂的过滤器。
 * 字符串文字必须用单引号或双引号括起来([?(@.color == 'blue')] 或者 [?(@.color == "blue")]).
 * <p>
 * https://github.com/json-path/JsonPath
 */
public class JsonPathUtils {
    Configuration jsonPathAsPathConfig;
    Configuration jsonPathAsValueConfig;

    public void LoadJsonPathConfig() {
        this.jsonPathAsPathConfig = Configuration.builder().options(
                Option.AS_PATH_LIST
                , Option.ALWAYS_RETURN_LIST
                , Option.SUPPRESS_EXCEPTIONS
                , Option.DEFAULT_PATH_LEAF_TO_NULL).build();
        this.jsonPathAsValueConfig = Configuration.builder().options(Option.ALWAYS_RETURN_LIST
                , Option.SUPPRESS_EXCEPTIONS
                , Option.DEFAULT_PATH_LEAF_TO_NULL).build();
    }


    /**
     * 获取json
     * @param jsonStr
     * @param jsonPath
     * @return
     */
    public Object getJsonPathVal(String jsonStr,String jsonPath){
        return JsonPath.read(jsonStr,jsonPath);
    }

    /**
     * 设置json中字段的值
     * @param jsonStr
     * @param jsonPath
     * @param val
     * @return
     */
    public String setJsonVal(String jsonStr,String jsonPath,Object val){
        String newJsonStr= JsonPath.parse(jsonStr).set(jsonPath,val).jsonString();
        return newJsonStr;
    }

    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "    \"store\": {\n" +
                "        \"book\": [\n" +
                "            {\n" +
                "                \"category\": \"reference\",\n" +
                "                \"author\": \"Nigel Rees\",\n" +
                "                \"title\": \"Sayings of the Century\",\n" +
                "                \"price\": 8.95\n" +
                "            },\n" +
                "            {\n" +
                "                \"category\": \"fiction\",\n" +
                "                \"author\": \"Evelyn Waugh\",\n" +
                "                \"title\": \"Sword of Honour\",\n" +
                "                \"price\": 12.99\n" +
                "            },\n" +
                "            {\n" +
                "                \"category\": \"fiction\",\n" +
                "                \"author\": \"Herman Melville\",\n" +
                "                \"title\": \"Moby Dick\",\n" +
                "                \"isbn\": \"0-553-21311-3\",\n" +
                "                \"price\": 8.99\n" +
                "            },\n" +
                "            {\n" +
                "                \"category\": \"fiction\",\n" +
                "                \"author\": \"J. R. R. Tolkien\",\n" +
                "                \"title\": \"The Lord of the Rings\",\n" +
                "                \"isbn\": \"0-395-19395-8\",\n" +
                "                \"price\": 22.99\n" +
                "            }\n" +
                "        ],\n" +
                "        \"bicycle\": {\n" +
                "            \"color\": \"red\",\n" +
                "            \"price\": 19.95\n" +
                "        }\n" +
                "    },\n" +
                "    \"expensive\": 10\n" +
                "}";

        //
        Map<String, Object> s = JsonPath.read(jsonStr, "$.store");
        System.out.println(s);

        String x= new JsonPathUtils().getJsonPathVal(jsonStr,"$.store..author").toString();
        System.out.println("color:"+x);

        net.minidev.json.JSONArray s2 = JsonPath.read(jsonStr, "$.store.book");
        System.out.println(s2);

        Map s3 = JsonPath.read(jsonStr, "$.store.book[0]");
        System.out.println(s3);

        String author = JsonPath.read(jsonStr, "$.store.book[0].author");
        String author2 = JsonPath.read(jsonStr, "$.store.['book'][0].['author']");
        System.out.println("author=" + author);
        System.out.println("author2=" + author2);

        // 获取book中所有author,这里book[*].author<==>book..author
        // 以下4种方式都等价
        net.minidev.json.JSONArray a = JsonPath.read(jsonStr, "$.store.book..author");
        net.minidev.json.JSONArray a2 = JsonPath.read(jsonStr, "$.store.book[*].author");
        net.minidev.json.JSONArray a33 = JsonPath.read(jsonStr, "$.store..author");
        net.minidev.json.JSONArray a34 = JsonPath.read(jsonStr, "$..author");
        System.out.println("a==" + a);
        System.out.println("a2==" + a2);
        System.out.println("a33==" + a33);
        System.out.println("a34==" + a34);

//        获取json的所有信息,等于读取整个json字符串
        net.minidev.json.JSONArray a3 = JsonPath.read(jsonStr, "$..*");
        System.out.println("a3=" + a3);

//        获取json中book价格<10的
        net.minidev.json.JSONArray a4 = JsonPath.read(jsonStr, "$.store.book[?(@.price<10)]");
        System.out.println("a3=" + a4);

//        获取json中book价格<expensive的
        net.minidev.json.JSONArray a5 = JsonPath.read(jsonStr, "$.store.book[?(@.price<$['expensive'])]");
        System.out.println("a5=" + a5);

       
    }


}
二、上面的方式,只适合读一次,因为每次调用JsonPath.read(...)都会解析文档,为了避免这个问题,可以先解析json
       /**
         * 二、上面的方式,只适合读一次,因为每次调用JsonPath.read(...)都会解析文档,为了避免这个问题,可以先解析json
         */
        Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonStr);
        JSONArray authorxx = JsonPath.read(doc, "$.store..author");
        System.out.println(authorxx);

三、JsonPath还提供了一个流畅的API。这也是最灵活的一个。

        /**
         * JsonPath还提供了一个流畅的API。这也是最灵活的一个。
         */
        ReadContext ctx=JsonPath.parse(jsonStr);
        List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");

        // 如下:获取json中所有author
        JSONArray jsonArray = ctx.read("$.store..author");
        System.out.println("jsonArray=="+jsonArray);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值