如何使用java搜索/查找JSON [英] How to search/find In JSON with java
问题描述
我有一个下面的JSON字符串,我想在JSON字符串中找到/搜索条件。
I have a below JSON string from the below i want to find/search criteria in JSON String.
1)。查找存在的键数。
2)。获取给定键的值(如果我们有数组)
1). To find the Number of keys present. 2). To get the values of given key(if we have array)
{
"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
}
我正在寻找像Groovy GPath语法的解决方案
I am looking a solution like Groovy GPath Syntax
- store.book - 此数组的大小。
- store.book [*]。category - 数组中密钥的出现次数。
- store.bicycle - 如果发现它必须返回真值
推荐答案
您还可以使用 JsonPath 项目由 REST Assured 。此JsonPath项目使用Groovy GPath表达式。在Maven你可以这样依赖它:
You can also use the JsonPath project provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
示例:
获取所有图书类别的列表:
To get a list of all book categories:
List<String> categories = JsonPath.from(json).get("store.book.category");
获取第一个图书类别:
String category = JsonPath.from(json).get("store.book[0].category");
获取最后一本书类别:
String category = JsonPath.from(json).get("store.book[-1].category");
获取价格在5到15之间的所有书籍:
Get all books with price between 5 and 15:
List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");
GPath非常强大,您可以在路径中使用更高阶函数和所有Groovy数据结构表达式。
GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.
这篇关于如何使用java搜索/查找JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!