JSONPath 表达式的使用

JSONPath 表达式的使用,第1张

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://outofmemory.cn/zaji/585511.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存