json解析工具jsonpath

JsonPath提供的json解析非常強大,它提供了類似正則表達式的語法,基本上可以滿足所有你想要獲得的json內(nèi)容。

引入

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

操作符

符號 描述
$ 要查詢的根元素。 這將啟動所有路徑表達式。
@ 正在處理的當(dāng)前節(jié)點。
* 通配符。 可在任何需要名稱或數(shù)字的地方使用。
.. 深層掃描。 可在需要名稱的任何地方使用。
.<name> 孩子節(jié)點
['<name>' (, '<name>')] 多個孩子
[<number> (, <number>)] 數(shù)組的下標(biāo)(從0開始),可寫多個。
[start:end] 數(shù)組的范圍
[?(<expression>)] 過濾表達式。 表達式結(jié)果必須為布爾值。

函數(shù)

可以在路徑的末尾調(diào)用函數(shù)-函數(shù)的輸入是路徑表達式的輸出。 函數(shù)輸出由函數(shù)本身決定。

函數(shù) 描述 輸出類型
min() 計算數(shù)組中最小的元素 double
max() 計算數(shù)組中最大的元素 double
avg() 計算數(shù)組所有元素的平均值 double
stddev() 計算數(shù)組所有元素的標(biāo)準(zhǔn)差 double
length() 計算數(shù)組的長度 int
sum() 計算數(shù)組所有元素的和 double

過濾器

過濾器是用于過濾數(shù)組的邏輯表達式。 典型的過濾器為[?(@.age > 18)],其中@代表當(dāng)前正在處理的節(jié)點。 可以使用邏輯運算符&&||創(chuàng)建更復(fù)雜的過濾器。 字符串文字必須用單引號或雙引號引起來([?(@.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
=~ 從左開始正則匹配字符串[?(@.name =~ /foo.*?/i)]
in 左元素存在右數(shù)組中[?(@.size in ['S', 'M'])]
nin 左元素不存在右數(shù)組中
subsetof 左是右的子集[?(@.sizes subsetof ['S', 'M', 'L'])]
anyof 左與右有交集[?(@.sizes anyof ['M', 'L'])]
noneof 左與右沒有交集[?(@.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);

返回類型

不確定路徑始終返回一個列表,如果路徑包含以下內(nèi)容,則該路徑是不確定的:

  • ..: 深度掃描
  • ?(<expression>): 表達式
  • [<number>, <number> (, <number>)]:數(shù)組多索引
#類型轉(zhuǎn)換 MappingProvider SPI提供了一個簡單的對象映射器
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);
#要獲取完整的泛型類型信息,請使用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 : 此選項使JsonPath對于缺少的葉子返回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: 即使路徑是確定的,此選項也將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']");
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容