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>
?
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 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.
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.
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.
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" } ]
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