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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28982412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:30:12  来源:igfitidea点击:

How to search/find In JSON with java

javarest-assuredsimplejsonrest-assured-jsonpath

提问by Ssire

I have a below JSON string from the below i want to find/search criteria in JSON String.

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

1). To find the Number of keys present. 2). To get the values of given key(if we have array)

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
}

I am looking a solution like Groovy GPath Syntax

我正在寻找像 Groovy GPath Syntax 这样的解决方案

  • store.book - size of this array.
  • store.book[*].category - how may times the key present in the array.
  • store.bicycle - if it found it has to return true value
  • store.book - 此数组的大小。
  • store.book[*].category - 数组中存在的键的次数。
  • store.bicycle - 如果发现它必须返回真值

回答by Johan

You can also use the JsonPathproject provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:

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

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

Examples:

例子:

To get a list of all book categories:

要获取所有书籍类别的列表:

List<String> categories = JsonPath.from(json).get("store.book.category");

Get the first book category:

获取第一个图书类别:

String category = JsonPath.from(json).get("store.book[0].category");

Get the last book category:

获取最后一本书类别:

String category = JsonPath.from(json).get("store.book[-1].category");

Get all books with price between 5 and 15:

获取价格在 5 到 15 之间的所有书籍:

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

GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.

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

回答by David Michael Gang

回答by Usman Yaqoob

First of all you have to add dependency

首先你必须添加依赖

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Then you can use this code:

然后你可以使用这个代码:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class Main {

    public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
        "<Result><ResultParameters><ResultParameter><Key>TransEndDate</Key><Value>20170731</Value></ResultParameter><ResultParameter><Key>Failed Reason</Key><Value>Operator 03058361178058365278 has no permission to perform the Check Balance service.</Value></ResultParameter><ResultParameter><Key>TransEndTime</Key><Value>123611</Value></ResultParameter></ResultParameters><ResultCode>2000</ResultCode><ResultType>0</ResultType><OriginatorConversationID>S_X20130129210125</OriginatorConversationID><ResultDesc>Initiator authentication error.</ResultDesc><TransactionID>000749213589</TransactionID><ConversationID>AG_20170731_00004c28e51f1f822e9e</ConversationID></Result>";

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);


            System.out.println("Element="+xmlJSONObj.getJSONObject("Result").getInt("ResultCode"));

        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

// in it i am searching an element which is present in a json object