java - 如何使用 Rest Assured 在 Response API 中获取两个具有相同名称的不同字段?

标签 java rest-assured rest-assured-jsonpath

我正在尝试使用 Rest-Assured 和 Java 为 GET API 创建测试自动化。

此 API 具有以下响应正文:

{
    "items": [
        {
            "id": "3185",
            "customer_id": "299",
            "region": "São Paulo",
            "region_id": 1234,
            "country_id": "BR",
            "street": [
                "Av Paulista"
            ],
            "company": "Teste",
            "telephone": "(19) 99999-9999",
            "postcode": "",
            "city": "Valinhos",
            "firstname": "N/A",
            "lastname": "N/A",
            "middlename": null,
            "prefix": null,
            "suffix": null,
            "person_type": "PF",
            "document": "43448871703",
            "state_registry": null,
            "created_at": "2019-07-24 13:03:29"
        },
        {
            "id": "3188",
            "customer_id": "299",
            "region": "São Paulo",
            "region_id": 1234,
            "country_id": "BR",
            "street": [
                "Av Paulista"
            ],
            "company": "Teste",
            "telephone": "(19) 99999-9999",
            "postcode": "",
            "city": "Valinhos",
            "firstname": "N/A",
            "lastname": "N/A",
            "middlename": null,
            "prefix": null,
            "suffix": null,
            "person_type": "PJ",
            "document": "84047942000115",
            "state_registry": null,
            "created_at": "2019-07-24 13:03:30"
        }
    ]
}

在此 API 响应中,有两个具有相同名称“id”的字段。如何获取这两个字段的值?

谢谢

最佳答案

看看这篇文章:https://techeplanet.com/parse-json-array-using-rest-assured/

    @Test
    public void verifyJSONArrayResponse() {
        JsonArray jsonArray = new JsonArray();

        jsonArray = given().baseUri("http://<your host>")
                .basePath("<your path>")
                .get().as(JsonArray.class);

        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
            System.out.println(jsonObject.get("id").getAsString());
        }
    }

不过,您需要对其进行一些调整,以便首先从顶级响应对象中提取items(您的数组)。

关于java - 如何使用 Rest Assured 在 Response API 中获取两个具有相同名称的不同字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218550/

相关文章:

java - 在其他系统上使用 Javamail 连接到 IMAP

java - 放心 Java : How to get header user and pass from setup method

rest-assured - 状况放心

java - 放心,JSON : verify absence of a value in a field

apache - org.apache.http.ConnectionClosedException : Premature end of chunk coded message body: closing chunk expected

java - 这个 Java 是否很好地近似了 @UIApplicationMain 在 Swift 中的工作方式?

java - 测试NG : @Parameters does not work

java - Windows 和 Linux 的文件路径名

java - 无法从放心响应中获取 Json 对象(json 格式)

java - 无法使用 JsonPath 库获取带空格的键值