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

jm81lzqq  于 2023-02-28  发布在  Java
关注(0)|答案(5)|浏览(168)

我有一个来自下面的JSON字符串,我想在JSON字符串中查找/搜索条件。
1.以查找存在的键数。
1.获取给定键的值(如果有数组)

{
    "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 -如果找到,则必须返回真值
0qx6xfy6

0qx6xfy61#

您也可以使用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数据结构。

8tntrjer

8tntrjer2#

首先,在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获取列表的List)

7gs2gvoe

7gs2gvoe3#

我会试试下面的库
https://github.com/jayway/JsonPath

  • ]

给你所有的书

pbgvytdp

pbgvytdp4#

首先,您必须添加依赖项

<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
mbjcgjjk

mbjcgjjk5#

我们可以编写通用的json实用程序,但在此之前,我们应该有org.json依赖关系应该存在于maven pom.xml中。
公共类PrintJsonPath_Version02 {

public static void main(String[] args) throws IOException {
    String jsonStr = new String(Files.readAllBytes(Paths.get(TestData.ECOMMERCE_TEST_DATA)));

    JSONObject jsonObject = new JSONObject(jsonStr);
    Map<String, Object> map = new HashMap<>();

    printJsonPath("", jsonObject, map);
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    }

}

private static void printJsonPath(String path, Object object, Map<String, Object> map) {
    Object value = "";

    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;
        for (String key : jsonObject.keySet()) {
            value = jsonObject.get(key);
            String newPath = path.isEmpty() ? key : path + "." + key;
            printJsonPath(newPath, value, map);
        }
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        for (int i = 0; i < jsonArray.length(); i++) {
            value = jsonArray.get(i);
            String newPath = path + "[" + i + "]";
            printJsonPath(newPath, value, map);
        }
    } else {
        if (!path.isEmpty() && path.charAt(0) == '.') {
            path = path.substring(1);
        }

        map.put(path, object);
    }
}

}

输出如下所示

左侧为JsonPath =右侧为值
订单[0]。客户。账单_address.city=班加罗尔订单[1]。商品[0]。产品标识= P003
订单[1].customer.phone:555-555-5678

相关问题