JsonPath —— JSON 解析神器

首发地址:http://www.54tianzhisheng.cn/2017/10/13/JsonPath/

真乃神器也,再复杂的 Json 都能给你解析出来,非常方便的获取 JSON 的内容,很强大!

语法简介

JsonPath描述
$根节点
@当前节点
.or[]子节点
..选择所有符合条件的节点
*所有节点
[]迭代器标示,如数组下标
[,]支持迭代器中做多选
[start:end:step]数组切片运算符
?()支持过滤操作
()支持表达式计算

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,
        "isbn": "0-553-21311-3"
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

导包:import com.jayway.jsonpath.JsonPath

解析代码:

//输出book[0]的author值
String author = JsonPath.read(json, "$.store.book[0].author");
System.out.println("author\t"+author);
//输出全部author的值,使用Iterator迭代
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
System.out.println("authors\t"+authors);

//输出book[*]中category == 'reference'的book
List<Object> books = JsonPath.read(json, "$.store.book[?(@.category == 'reference')]");
System.out.println("books\t"+books);
//输出book[*]中category == 'reference'的book或者
List<Object> books2 = JsonPath.read(json, "$.store.book[?(@.category == 'reference' || @.price>10)]");
System.out.println("books2\t"+books2);

//输出book[*]中category == 'reference'的book的author
List<Object> books1 = JsonPath.read(json, "$.store.book[?(@.category == 'reference')].author");
System.out.println("books1\t"+books1);

//输出book[*]中price>10的book
List<Object> b1 = JsonPath.read(json, "$.store.book[?(@.price>10)]");
System.out.println("b1"+b1);

//输出book[*]中含有isbn元素的book
List<Object> b2 = JsonPath.read(json, "$.store.book[?(@.isbn)]");
System.out.println("b2"+b2);

//输出该json中所有price的值
List<Double> prices = JsonPath.read(json, "$..price");
System.out.println("prices"+prices);

//输出该json中所有title的值
List<Double> title = JsonPath.read(json, "$..title");
System.out.println("title"+title);
//输出该json中book 0,1的值
List<Double> book01 = JsonPath.read(json, "$..book[0,1]");
System.out.println("book01"+book01);
/* //输出该json中book 0,1的值
List<Double> book012 = JsonPath.read(json, "$..book[-2:]");
System.out.println("book012"+book012);*/

//可以提前编辑一个路径,并多次使用它
JsonPath path = JsonPath.compile("$.store.book[*]");
List<Object> b3 = path.read(json);
System.out.println("path\t"+path+"\n"+b3);

用法比较简单,多使用几次就会使用了!文章主要参考网上!原谅很多天不跟博的我现在竟然这样水了这么一篇文章,哈哈!实在是忙!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhisheng_blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值