1. 概述
本快速教程將介紹如何使用 JsonPath 來統計 JSON 文檔中的對象和數組。
JsonPath 提供了一種標準化的機制來遍歷 JSON 文檔中的特定部分。 我們可以説 JsonPath 就像 XPath 是對 XML 的一樣。
2. 所需依賴
我們使用了以下 JsonPath Maven 依賴項,它當然可以在 Maven Central 上找到。
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.9.0</version>
</dependency>3. 示例 JSON
以下 JSON 將被用於説明示例:
{
"items":{
"book":[
{
"author":"Arthur Conan Doyle",
"title":"Sherlock Holmes",
"price":8.99
},
{
"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
}
},
"url":"mystore.com",
"owner":"baeldung"
}4. 統計 JSON 對象
根元素由美元符號“$”表示。在下面的 JUnit 測試中,我們調用 JsonPath.read() 方法,並傳入 JSON String 和我們想要統計的 JSON 路徑“$”:
public void shouldMatchCountOfObjects() {
Map<String, String> objectMap = JsonPath.read(json, "$");
assertEquals(3, objectMap.keySet().size());
}通過統計結果 Map 的大小,我們就能知道在 JSON 結構中,給定路徑內的元素數量。
5. 統計 JSON 數組大小
在以下 JUnit 測試中,我們查詢 JSON 以查找包含所有 書籍 的數組,該數組位於 items 元素下:
public void shouldMatchCountOfArrays() {
JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
assertEquals(2, jsonArray.size());
}6. 結論
在本文中,我們介紹瞭如何在 JSON 結構中進行計數的一些基本示例。
您可以在 官方 JsonPath 文檔 中探索更多路徑示例。