Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e.,

  [{
    "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

like image 255
Kavana Avatar asked Feb 08 '16 06:02

Kavana


People also ask

How do you parse a JSON object in Restassured?

We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute. We shall first send a GET request via Postman on a mock API URL and observe the Response body.

How can we get size of JSON array in Rest assured?

We can get the size of an array within a nested JSON in Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string. Finally, to obtain JSON array size, we have to use the size method.


2 Answers

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;
like image 194
Anoop Philip Avatar answered Oct 13 '22 01:10

Anoop Philip


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");
like image 32
Kruti Patel Avatar answered Oct 13 '22 00:10

Kruti Patel