簡體   English   中英

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

[英]How to search/find In JSON with java

我有一個下面的 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 Syntax 這樣的解決方案

  • store.book - 此數組的大小。
  • store.book[*].category - 數組中存在的鍵的次數。
  • store.bicycle - 如果發現它必須返回真值

您還可以使用REST Assured提供的JsonPath項目。 這個 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 數據結構。

首先你必須添加依賴

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

然后你可以使用這個代碼:

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 03058361178\03058365278 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 

首先在pom中添加json-path依賴

<dependency>
     <groupId>com.jayway.jsonpath</groupId>
     <artifactId>json-path</artifactId>
     <version>2.2.0</version>
</dependency>

在基類中創建一個可以重用的實用程序:

 public static String getValueFromJsonPath(String apiResponse, String jsonPath) {
        return JsonPath.read(apiResponse, jsonPath);
    }

使用此方法的一個示例:

getValueFromJsonPath(apiResponse, "$.store.book[0].category");

注意:根據預期結果創建具有不同返回類型的重載方法(例如用於從 json 獲取列表的列表)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM