JsonPath全英文文档学习

1、文档地址

github地址

2、引入依赖

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.9.0</version>
</dependency>

在这里插入图片描述

全英文文档可借助谷歌浏览器翻译

但谷歌浏览器无法翻译
在这里插入图片描述

3、浏览翻译问题修复

因为谷歌翻译下架了。所以下载一个别的强大的浏览器edge浏览器

下载安装沉浸式翻译插件

翻译成功
在这里插入图片描述

can you speck chinese ,yes

4、文档学习

4.1、Operator

在这里插入图片描述

4.2、Functions

在这里插入图片描述
在这里插入图片描述

4.3、Filter 运算符

在这里插入图片描述

在这里插入图片描述

4.4、json示例

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

5、实战

5.1、获取json数组下的多个元素

$.父级.key[*].元素

 List<String> authorList = JsonPath.read(jsonStr, "$.store.book[*].author");
 List<String> categoryList = JsonPath.read(jsonStr, "$.store.book[*].category");

        log.info("authorList:{}",authorList);
        log.info("categoryList:{}",categoryList);
      

在这里插入图片描述

必须填写父级一层一层找下去,否则爆异常
在这里插入图片描述

5.2、获取json数组下的多个元素(循环遍历时无元素自动占位)

在这里插入图片描述
比如取book下的isbn。第0,第1位下无此元素。则第2,3位自动占位到list的0,1位

List<String> isbnList = JsonPath.read(jsonStr, "$.store.book[*].isbn");
log.info("isbnList:{}",isbnList);

在这里插入图片描述

###如果多次使用JsonPath.read()需要先解析json。拿到object后。在调用.read()方法

        // 初始化一次
        Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonStr);

        List<String> authorList = JsonPath.read(document, "$.store.book[*].author");
        List<String> categoryList = JsonPath.read(document, "$.store.book[*].category");
        List<String> isbnList = JsonPath.read(document, "$.store.book[*].isbn");
        log.info("authorList:{}",authorList);
        log.info("categoryList:{}",categoryList);
        log.info("isbnList:{}",isbnList);

5.3、获取json数组下的单个元素

直接取jsonArray下元素:

        String author0 = JsonPath.read(document, "$.store.book[0].author");
        log.info("author0:{}",author0);

在这里插入图片描述

动态遍历获取jsonArray下元素

 if (!CollectionUtils.isEmpty(authorList)) {
            for (int i = 0; i < authorList.size(); i++) {
                // 拼接动态jsonPath
                String jsonPathStrPrefix = "$.store.book[";
                String jsonPathStrSuffix = "].author";
                String author = JsonPath.read(document, jsonPathStrPrefix.concat(String.valueOf(i)).concat(jsonPathStrSuffix));
                System.out.println(author);
            }
        }

在这里插入图片描述

5.4、获取json数组下存在某个元素的其他元素集合

ReadContext ctx = JsonPath.parse(jsonStr);

List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");

System.out.println("authorsOfBooksWithISBN:"+authorsOfBooksWithISBN);

在这里插入图片描述

5.5、根据json数组重组List<Map<String,Object>>

获取价格>10的 books数组

 List<Map<String, Object>> expensiveBooks = JsonPath
                .using(Configuration.defaultConfiguration())
                .parse(jsonStr)
                .read("$.store.book[?(@.price > 10)]", List.class);

或者

List<Map<String, Object>> books =  JsonPath.parse(jsonStr)
                .read("$.store.book[?(@.price > 10)]");

在这里插入图片描述

5.6、时间戳转date

  String json = "{\"date_as_long\" : 1411455611975}";

        Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
        System.out.println("date:"+date);

在这里插入图片描述

5.7、json数组转对象

Book

package com.ljs.gulimall.product.entity;

import lombok.Data;

@Data
public class Book {
    private String category;

    private String author;

    private String title;

    private Double price;

    private String isbn;
}

Book book = JsonPath.parse(jsonStr).read("$.store.book[0]", Book.class);
System.out.println("book:"+book);

5.8、筛选器获取List<Map<String,Object>>

获取json数组book下category元素是fiction且价格小于10的集合

  Filter cheapFictionFilter = filter(
                where("category").is("fiction").and("price").lte(10D)
        );
        List<Map<String, Object>> books =
                parse(jsonStr).read("$.store.book[?]", cheapFictionFilter);
        System.out.println("books:"+books);

在这里插入图片描述

5.9、筛选器根据字段是否存在获取List<Map<String,Object>>

 Filter fooOrBar = filter(
                where("isbn").exists(true)).or(where("category").exists(true)
        );

        Filter fooAndBar = filter(
                where("isbn").exists(true)).and(where("foo").exists(true)
        );
        List<Map<String, Object>> bookAnd =
                parse(jsonStr).read("$.store.book[?]", fooAndBar);
        System.out.println("bookAnd:"+bookAnd);

        List<Map<String, Object>> bookOr =
                parse(jsonStr).read("$.store.book[?]", fooOrBar);
        System.out.println("bookOr:"+bookOr);

在这里插入图片描述

5.10、根据json数组三参数获取List< Object>

   Predicate booksWithISBN = new Predicate() {
            @Override
            public boolean apply(PredicateContext ctx) {
                return ctx.item(Map.class).containsKey("isbn");
            }
        };

        List<Object> books =
                parse(jsonStr).read("$.store.book[?].isbn", List.class, booksWithISBN);
        System.out.println("books:"+books);

在这里插入图片描述

5.11、set元素值

String newJson = JsonPath.parse(jsonStr).set("$['store']['book'][0]['author']", "ljs").jsonString();
System.out.println("jsonStr:"+newJson);

在这里插入图片描述

5.12、避免空路径异常(DEFAULT_PATH_LEAF_TO_NULL)

在这里插入图片描述

 Configuration configuration = Configuration.defaultConfiguration();

//Works fine
String gender0 = JsonPath.using(configuration).parse(str).read("$[0]['gender']");
//PathNotFoundException thrown
String gender1 = JsonPath.using(configuration).parse(str).read("$[1]['gender']");

System.out.println("gender0:"+gender0);
System.out.println("gender1:"+gender1);

在这里插入图片描述

    Configuration conf2 = configuration.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);

//Works fine
String gender0 = JsonPath.using(conf2).parse(str).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(str).read("$[1]['gender']");
System.out.println("gender0:"+gender0);
System.out.println("gender1:"+gender1);

在这里插入图片描述

5.13、返回列表(ALWAYS_RETURN_LIST)

 Configuration configuration = Configuration.defaultConfiguration();
List<String> genders0 = JsonPath.using(configuration).parse(str).read("$[0]['gender']");
System.out.println("genders0:"+genders0);

在这里插入图片描述

Configuration configuration = Configuration.defaultConfiguration();
Configuration conf2 = configuration.addOptions(Option.ALWAYS_RETURN_LIST);

//Works fine
List<String> genders0 = JsonPath.using(conf2).parse(str).read("$[0]['gender']");
System.out.println("genders0:"+genders0);

在这里插入图片描述

5.14、不从路径评估传播异常(SUPPRESS_EXCEPTIONS)

如果存在选项 ALWAYS_RETURN_LIST,将返回一个空列表

如果选项 ALWAYS_RETURN_LIST 不存在,则返回 null

5.15、从路径评估抛出异常设置(REQUIRE_PROPERTIES)

Configuration configuration = Configuration.defaultConfiguration();
//Works fine
List<String> genders = JsonPath.using(configuration).parse(str).read("$[*]['gender']");
System.out.println("genders:"+genders);

在这里插入图片描述

Configuration configuration = Configuration.defaultConfiguration();
Configuration conf2 = configuration.addOptions(Option.REQUIRE_PROPERTIES);

//PathNotFoundException thrown
List<String> genders = JsonPath.using(conf2).parse(str).read("$[*]['gender']");
System.out.println("genders:"+genders);

在这里插入图片描述

  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值