JSONPath 表达式的使用

一、JSONPath使用需要的包
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
二、使用说明

1、JSONPath是xpath在json的应用
2、JSONPath 是参照xpath表达式来解析xml文档的方式,json数据结构通常是匿名的并且不一定需要有根元素。
3、JSONPath 用一个抽象的名字$来表示最外层对象
4、JSONPath 允许使用通配符 * 表示所以的子元素名和数组索引

三、JSONPath表达式语法

JSONPath 表达式可以使用.符号解析json:
$.store.book[0].title
或者使用[]符号
$['store']['book'][0]['title']

四、测试实例

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 } } } 

首先,读取json文件,使用commons.io的 FileUtils的readFileToString方法:

String path =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"test.json"; String jsonString = FileUtils.readFileToString(new File(path),"utf-8"); ReadContext context = JsonPath.parse(json); 

其次,输出book[1]的author值。有两种方法:
方法一:

JsonPath.read(json,"$.store.book[1].author");
或
context.read("$.store.book[1].author");
输出:Evelyn Waugh 

方法二:

JsonPath.read(json,"$['store']['book'][1]['author']");
context.read("$['store']['book'][1]['author']");

输出:Evelyn Waugh 

//输出book[*]中category == 'reference'的book

List<Object> categorys = context.read("$.store.book[?(@.category == 'reference')]");
for(Object st: categorys){ System.out.println(st.toString()); } 输出: {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95} 

//输出book[*]中price>10的book

List<Object> prices = context.read("$.store.book[?(@.price>10)]");
for(Object p:prices){ System.out.println(p.toString()); } 输出:{category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99, isbn=0-553-21311-3} 

//bicycle[*]中含有color元素的bicycle

List<Object> color = context.read("$.store.bicycle[?(@.color)]");
for(Object is :color){ System.out.println(is.toString()); } 输出://{color=red, price=19.95} 

//输出该json中所有price的值

List<Object> pp = context.read("$..price");
for(Object p :pp){ System.out.println(p.toString()); } 输出: 8.95 12.99 19.95 List<String> authors = context.read("$.store.book[*].author"); for (String str : authors) { System.out.println(str); } 输出:Nigel Rees Evelyn Waugh 
五、XPATH 和 JSONPath获取元素的方法比较

[]在xpath表达式总是从前面的路径来操作数组,索引是从1开始。
使用JOSNPath的[]操作符操作一个对象或者数组,索引是从0开始。


 


作者:森迪
链接:https://www.jianshu.com/p/94ddacae5d55
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

转载于:https://www.cnblogs.com/maybach/p/8304871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值