top of page
Search

How to read array of objects in response in RestAssured in POJO fashion

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

To read an array of objects in a response using RestAssured in a POJO (Plain Old Java Object) fashion, you can leverage the `Response` class provided by RestAssured along with the Jackson library for JSON deserialization. Here's an example of how you can achieve this:


1. Create a POJO representing the object in the array:

First, define a POJO class that represents the structure of each object in the array. Let's assume you have a User object with properties like name, age, and email. Here's an example:


public class User {
    private String name;
    private int age;
    private String email;

    // Getter and setter methods

    // You can also add any additional methods or constructors as per your requirements
}

2. Send the API request and deserialize the response into an array of objects:

Next, send the API request using RestAssured and retrieve the response. Then, deserialize the response into an array of objects using the Jackson library. Here's an example:


import io.restassured.RestAssured;
import io.restassured.response.Response;
import com.fasterxml.jackson.databind.ObjectMapper;

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

// Deserialize the response into an array of User objects
ObjectMapper objectMapper = new ObjectMapper();
User[] users = objectMapper.readValue(response.getBody().asString(), User[].class);


In this example, we send a GET request to retrieve the response from `https://api.example.com/users`, and the response is stored in the `response` variable. We create an instance of the `ObjectMapper` class from the Jackson library, which is responsible for deserializing the JSON response into an array of User objects.


Using the `readValue()` method of the `ObjectMapper` class, we deserialize the response's body (obtained with `response.getBody().asString()`) into an array of User objects. The second argument of `readValue()` specifies the type of the target object, which is `User[].class` in this case.


After deserialization, the `users` variable will contain an array of User objects representing the response data.


Now, you can iterate over the `users` array and access the properties of each User object as per your requirements.


By combining RestAssured with the Jackson library for JSON deserialization, you can read an array of objects in a response and map them to POJOs in a clean and structured fashion.

 
 
 

Recent Posts

See All

Comentários


Never Miss a Post. Subscribe Now!

Find new exciting ways to dominate the IT Automation industry

Thanks for submitting!

bottom of page