Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest Assured - deserialize Response JSON as List<POJO>

I have a POJO Artwork. I'm retrieving a List of those objects from a RESTful webservice in the HTTP response body in JSON format. I'm trying to write a Rest Assured-based test that would analyze the returned list. The code looks like this:

Response response = get("/artwork"); List returnedArtworks = response.getBody().as(List.class) 

The problem is, I can't get Rest Assured to parse the returned JSON as List<Artwork>. Instead, I get a List<LinkedHashMap>. The map has a proper structure, i.e. could be mapped by Jackson to Artwork object, but I'd like to avoid mapping it manually.

JSON mappings in my model are OK, because when I map single object like this:

Artwork returnedArtwork = response.getBody().as(Artwork.class); 

it works fine.

Is it possible to get returnedArtworks as List<Artwork>?

like image 803
Wojtek Avatar asked Feb 12 '14 10:02

Wojtek


People also ask

How do you read a JSON response body using rest assured?

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 do you validate complex JSON response in Rest assured?

We can verify the JSON response body using Assertions in Rest Assured. This is done with the help of the Hamcrest Assertion. It uses the Matcher class for Assertion. We shall send a GET request via Postman on a mock API, observe the Response.

Why we use POJO class in Rest assured?

POJO classes are used to represent data. POJO Class will contain only default constructor, private data members, and public setter and getter methods for every data member. Setter methods are used to set the value to the variable. Getter methods are used to get the value from the variable.


2 Answers

You can do this:

List<Artwork> returnedArtworks = Arrays.asList(response.getBody().as(Artwork[].class)); 

The trick is to deserialize JSON to an array of objects (because there is no difference between the JSON string of an array or a list), then convert the array to a list.

like image 163
volatilevar Avatar answered Sep 22 '22 06:09

volatilevar


this solution works for version 3.0.2 (io.restassured):

  JsonPath jsonPath = RestAssured.given()      .when()      .get("/order")      .then()      .assertThat()      .statusCode(Response.Status.OK.getStatusCode())      .assertThat()      .extract().body().jsonPath();    List<Order> orders = jsonPath.getList("", Order.class); 

This will extract the objects for a structure like this:

public class Order {  private String id;  public String getId(){ return id; }  public void setId(String id){ this.id = id; }   } 

with the given json:

[  { "id" : "5" },  { "id" : "6" } ] 
like image 30
Seren Avatar answered Sep 21 '22 06:09

Seren