1. Overview
1.概述
In this quick tutorial, we’ll explore how to use JsonPath to count objects and arrays in a JSON document.
在这个快速教程中,我们将探讨如何使用JsonPath来计算JSON文档中的对象和数组。
JsonPath provides a standard mechanism to traverse through specific parts of a JSON document. We can say JsonPath is to JSON what XPath is to XML.
JsonPath提供了一个标准的机制来遍历一个JSON文档的特定部分。我们可以说JsonPath对JSON的作用就像XPath对XML一样。
2. Required Dependencies
2.所需的依赖性
We’re using the following JsonPath Maven dependency, which is, of course, available on Maven Central:
我们使用以下JsonPathMaven依赖,当然,该依赖可在Maven中心获得。
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
3. Sample JSON
3.JSON样本
The following JSON will be used to illustrate the examples:
下面的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. Count JSON Objects
4.计算JSON对象
The root element is denoted by the Dollar symbol “$”. In the following JUnit test, we call JsonPath.read() with the JSON String and the JSON path “$” that we want to count:
根元素是由美元符号”$”表示的。在下面的JUnit测试中,我们调用JsonPath.read()的JSONString和我们要计算的JSON路径”$”。
public void shouldMatchCountOfObjects() {
Map<String, String> objectMap = JsonPath.read(json, "$");
assertEquals(3, objectMap.keySet().size());
}
By counting the size of the resulting Map, we know how many elements are at the given path within the JSON structure.
通过计算产生的Map的大小,我们知道在JSON结构中的给定路径上有多少元素。
5. Count JSON Array Size
5.计算JSON数组大小
In the following JUnit test, we query the JSON to find the array containing all books under the items element:
在下面的JUnit测试中,我们查询JSON以找到包含items元素下所有book的数组。
public void shouldMatchCountOfArrays() {
JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
assertEquals(2, jsonArray.size());
}
6. Conclusion
6.结语
In this article, we’ve covered some basic examples on how to count items within a JSON structure.
在这篇文章中,我们已经介绍了一些关于如何在JSON结构中计算项目的基本例子。
You can explore more path examples in the official JsonPath docs.
你可以在官方的JsonPath文档中探索更多的路径实例。
As always, the code examples can be found in the GitHub repository.
一如既往,代码示例可以在GitHub仓库中找到。