gpt4 book ai didi

java - 如何使用 java 在 JSON 中搜索/查找

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:58 27 4
gpt4 key购买 nike

我有下面的 JSON 字符串,我想在 JSON 字符串中查找/搜索条件。

  1. 找到存在的键数。
  2. 获取给定键的值(如果我们有数组)
    {
"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 语法的解决方案

  • store.book - 这个数组的大小。
  • store.book[*].category - 数组中出现的键的次数。
  • store.bicycle - 如果发现必须返回真值

最佳答案

您还可以使用 JsonPath项目提供REST Assured .这个 JsonPath 项目使用 Groovy GPath 表达式。在 Maven 中,您可以像这样依赖它:

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

示例:

获取所有图书类别的列表:

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 之间的所有书籍:

List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");

GPath 非常强大,您可以在路径表达式中使用高阶函数和所有 Groovy 数据结构。

关于java - 如何使用 java 在 JSON 中搜索/查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28982412/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com