JsonPath提供的json解析非常強(qiáng)大富寿,它提供了類似正則表達(dá)式的語(yǔ)法区赵,基本上可以滿足所有你想要獲得的json內(nèi)容汗洒。
引入
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
操作符
符號(hào) | 描述 |
---|---|
$ | 要查詢的根元素。 這將啟動(dòng)所有路徑表達(dá)式崩溪。 |
@ | 正在處理的當(dāng)前節(jié)點(diǎn)浅役。 |
* | 通配符。 可在任何需要名稱或數(shù)字的地方使用悯舟。 |
.. | 深層掃描担租。 可在需要名稱的任何地方使用砸民。 |
.<name> | 孩子節(jié)點(diǎn) |
['<name>' (, '<name>')] | 多個(gè)孩子 |
[<number> (, <number>)] | 數(shù)組的下標(biāo)(從0開(kāi)始)抵怎,可寫(xiě)多個(gè)奋救。 |
[start:end] | 數(shù)組的范圍 |
[?(<expression>)] | 過(guò)濾表達(dá)式。 表達(dá)式結(jié)果必須為布爾值反惕。 |
函數(shù)
可以在路徑的末尾調(diào)用函數(shù)-函數(shù)的輸入是路徑表達(dá)式的輸出尝艘。 函數(shù)輸出由函數(shù)本身決定。
函數(shù) | 描述 | 輸出類型 |
---|---|---|
min() | 計(jì)算數(shù)組中最小的元素 | double |
max() | 計(jì)算數(shù)組中最大的元素 | double |
avg() | 計(jì)算數(shù)組所有元素的平均值 | double |
stddev() | 計(jì)算數(shù)組所有元素的標(biāo)準(zhǔn)差 | double |
length() | 計(jì)算數(shù)組的長(zhǎng)度 | int |
sum() | 計(jì)算數(shù)組所有元素的和 | double |
過(guò)濾器
過(guò)濾器是用于過(guò)濾數(shù)組的邏輯表達(dá)式姿染。 典型的過(guò)濾器為[?(@.age > 18)]
背亥,其中@
代表當(dāng)前正在處理的節(jié)點(diǎn)。 可以使用邏輯運(yùn)算符&&
和||
創(chuàng)建更復(fù)雜的過(guò)濾器悬赏。 字符串文字必須用單引號(hào)或雙引號(hào)引起來(lái)([?(@.color == 'blue')]
或[?(@.color == "blue")]
)狡汉。
操作符 | 描述 |
---|---|
== | left is equal to right (note that 1 is not equal to '1') |
!= | left is not equal to right |
< | left is less than right |
<= | left is less or equal to right |
> | left is greater than right |
>= | left is greater than or equal to right |
=~ | 從左開(kāi)始正則匹配字符串[?(@.name =~ /foo.*?/i)]
|
in | 左元素存在右數(shù)組中[?(@.size in ['S', 'M'])]
|
nin | 左元素不存在右數(shù)組中 |
subsetof | 左是右的子集[?(@.sizes subsetof ['S', 'M', 'L'])]
|
anyof | 左與右有交集[?(@.sizes anyof ['M', 'L'])]
|
noneof | 左與右沒(méi)有交集[?(@.sizes noneof ['M', 'L'])]
|
size | 左邊(數(shù)組或字符串)的大小應(yīng)與右邊匹配 |
empty | 左邊(數(shù)組或字符串)應(yīng)為空 |
例子
{
"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
}
JsonPath | 結(jié)果描述 | 結(jié)果 |
---|---|---|
$.store.book[*].author | The authors of all books | ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"] |
$..author | All authors | ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"] |
$.store.* | All things, both books and bicycles | |
$.store..price | The price of everything | [8.95,12.99, 8.99, 22.99,19.95] |
$..book[2] | The third book | |
$.book[-2] | The second to last book | |
$..book[0,1] | The first two books | |
$..book[:2] | All books from index 0 (inclusive) until index 2 (exclusive) | |
$..book[1:2] | All books from index 1 (inclusive) until index 2 (exclusive) | |
$..book[-2:] | Last two books | |
$..book[2:] | Book number two from tail | |
$..book[?(@.isbn)] | All books with an ISBN number | |
$.store.book[?(@.price < 10)] | All books in store cheaper than 10 | |
$..book[?(@.author =~ /*.REES/i)] | All books matching regex (ignore case) | |
$..* | Give me every thing | |
$..book.length() | The number of books | [4] |
api
#方式1
String json = "...";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
#方式2:只需讀取一次json
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");
#方式3
String json = "...";
ReadContext ctx = JsonPath.parse(json);
List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
List<Map<String, Object>> expensiveBooks = JsonPath
.using(configuration)
.parse(json)
.read("$.store.book[?(@.price > 10)]", List.class);
返回類型
不確定路徑始終返回一個(gè)列表,如果路徑包含以下內(nèi)容闽颇,則該路徑是不確定的:
-
..
: 深度掃描 -
?(<expression>)
: 表達(dá)式 -
[<number>, <number> (, <number>)]
:數(shù)組多索引
#類型轉(zhuǎn)換 MappingProvider SPI提供了一個(gè)簡(jiǎn)單的對(duì)象映射器
String json = "{\"date_as_long\" : 1411455611975}";
Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
#如果將JsonPath配置為使用JacksonMappingProvider或GsonMappingProvider盾戴,您甚至可以將JsonPath輸出直接映射到POJO。
Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
#要獲取完整的泛型類型信息兵多,請(qǐng)使用TypeRef尖啡。
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};
List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);
設(shè)置值
String newJson = JsonPath.parse(json).set("$['store']['book'][0]['author']", "Paul").jsonString();
配置
#json
[
{
"name" : "john",
"gender" : "male"
},
{
"name" : "ben"
}
]
Configuration conf = Configuration.defaultConfiguration();
//Works fine
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
//PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");
#DEFAULT_PATH_LEAF_TO_NULL : 此選項(xiàng)使JsonPath對(duì)于缺少的葉子返回null。
Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
//Works fine
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
#ALWAYS_RETURN_LIST: 即使路徑是確定的剩膘,此選項(xiàng)也將JsonPath配置為返回類型為列表衅斩。
Configuration conf = Configuration.defaultConfiguration();
//ClassCastException thrown
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
Configuration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);
//Works fine
List<String> genders0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");