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
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.
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.
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");
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With