简体   繁体   中英

How to fetch JSON object from Json array in REstAssured

Can anyone please help me to solve this scenario:

I am new to RestAssured and handling JSON in our automation script. I have an API whose response is JSONArray ie,

  [{
    "id": 1002,
    "entity": "testcase",
    "fieldName": "TextName",
    "displayName": "Name"
  }, {
    "id": 1003,
    "entity": "testcase",
    "fieldName": "steps",
    "displayName": "TestSteps"
  }]

While automation, for verification i need to fetch the reponse. I have tried the below one but not getting expected output

 String API = "/field/entity/testcase"
 Response response = given().auth().preemptive().basic("test.manager",     "test.manager").when().get(API);
    JSONObject JSONResponseBody = new   JSONObject(response.body().asString());
    Assert.assertEquals(JSONResponseBody.getString("fieldName"), "TextName");

and also i tried with this:

    JSONArray array = new JSONArray();
    JsonObject JSONResponseBody = array.getJsonObject(0);

Thanks Inadvance

These kind of validation can achieve directly using restAssured - ValidatableResponseOptions itself

    String API = "/field/entity/testcase"
    given().auth().preemptive().basic("test.manager", "test.manager").
    when().get(API).
    then().assertThat().body("fieldName[0]", equalTo("TextName");

Note - "equalTo" validation needs following static import

import static org.hamcrest.Matchers.equalTo;

You should try this:

String API = "/field/entity/testcase"
Response response = given().auth().preemptive().basic("test.manager", "test.manager").when().get(API);
JSONArray JSONResponseBody = new   JSONArray(response.body().asString());
Assert.assertEquals(JSONResponseBody.getJsonObject(0).getString("fieldName"), "TextName");

Just as another idea of how to do this, I would do it maybe like this instead:

ValidatableResponse statusResponse = givenJsonRequest().when()
    .get("/field/entity/test").then();
ArrayList<Map<String,?>> jsonAsArrayList = statusResponse.extract()
    .jsonPath().get("");
Optional<Map<String,?>> filtered = jsonAsArrayList.stream()
    .filter(m -> m.get("fieldName1").equals("Whatever1"))
    .filter(m -> m.get("jsonObject").toString().contains("Whatever2"))
    .findFirst();
Assert.assertTrue(filtered.isPresent(), "Test expected a result after filtering.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM