top of page
Search

How to read array of objects in response in RestAssured

  • Writer: Dev Raj Sinha
    Dev Raj Sinha
  • Jun 19, 2023
  • 2 min read

To read an array of objects in the response using RestAssured, you can leverage the `JsonPath` class provided by RestAssured. The `JsonPath` class allows you to parse the response JSON and extract data from it. Here's an example of how you can read an array of objects in the response:


import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

Response response = RestAssured.get("https://api.example.com/endpoint");

// Parse the response JSON using JsonPath
JsonPath jsonPath = response.jsonPath();

// Read the array of objects from the response
List<Map<String, Object>> objects = jsonPath.getList("arrayName");

// Iterate over the array and access object properties
for (Map<String, Object> object : objects) {
    String property1 = object.get("property1").toString();
    int property2 = Integer.parseInt(object.get("property2").toString());
    // Access other properties as needed
}


In this example, we send a GET request using RestAssured and obtain the response. We then create a `JsonPath` object from the response using `response.jsonPath()`. The `arrayName` represents the name of the array in the response JSON.


Next, we use the `getList()` method of `JsonPath` to extract the array of objects from the response. The `getList()` method returns a list of `Map<String, Object>`, where each map represents an object in the array.


We can then iterate over the list of objects and access their properties using the `get()` method of the `Map` object. In the example, we access the "property1" and "property2" properties of each object.


You can modify the example according to your specific JSON structure and property names. Additionally, you can use the appropriate data types or cast the values to the desired types based on your requirements.


By using the `JsonPath` class in RestAssured, you can easily read an array of objects from the response and access their properties for further processing or assertions.

 
 
 

Recent Posts

See All

Comments


Never Miss a Post. Subscribe Now!

Find new exciting ways to dominate the IT Automation industry

Thanks for submitting!

bottom of page