一颖变、JSONPath使用需要的包
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
二、使用說(shuō)明
1马胧、JSONPath是xpath在json的應(yīng)用
2肛走、JSONPath 是參照xpath表達(dá)式來(lái)解析xml文檔的方式,json數(shù)據(jù)結(jié)構(gòu)通常是匿名的并且不一定需要有根元素朽色。
3、JSONPath 用一個(gè)抽象的名字$來(lái)表示最外層對(duì)象
4抱冷、JSONPath 允許使用通配符 * 表示所以的子元素名和數(shù)組索引
三梢褐、JSONPath表達(dá)式語(yǔ)法
JSONPath 表達(dá)式可以使用.符號(hào)解析json:
['store']['book'][0]['title']
四、測(cè)試實(shí)例
Json文件內(nèi)容如下:
{ "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
更多請(qǐng)參考https://blog.csdn.net/qq_20641565/article/details/77162868
五铛纬、XPATH 和 JSONPath獲取元素的方法比較
[]在xpath表達(dá)式總是從前面的路徑來(lái)操作數(shù)組,索引是從1開(kāi)始告唆。
使用JOSNPath的[]操作符操作一個(gè)對(duì)象或者數(shù)組,索引是從0開(kāi)始镊屎。
image.png