Search code examples
javarest-assuredrest-assured-jsonpath

How to get two different fields with the same name in a Response API using Rest Assured?


I'm trying to create a Test Automation for a GET API using Rest-Assured and Java.

This API has the follow response body:

{
    "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"
        }
    ]
}

In this API response there is two fields with the same name "id". How can I get the value of these two fields?

Thanks


Solution

  • Take a look at this article: 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());
            }
        }
    

    You'll need to adjust it a bit though, to extract items first (your array) from a top-level response object.