Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Assured - Generic List deserialization

People also ask

What is deserialization in Rest assured?

In REST APIs, the process of deserialization is performed especially for the JSON responses we receive from the API. ​ So, when we say we are deserializing the JSON, this means we convert the JSON format into a type we prefer, most frequently POJO (Plain Old Java Object) classes.

What is ObjectMapper in Rest assured?

Interface ObjectMapperAn object mapper is used to serialize and deserialize a Java object to and from a String, byte[] or InputStream. REST Assured provides mappers for XML and JSON out of the box (see ObjectMapperType ) but you can implement this interface to roll your own mapper implementations for custom formats.


I found a way to achieve what I wanted:

List<Person> persons = given().when().get("person/").as(Person[].class);

UPDATE: Using Rest-Assured 1.8.1, looks like cast to List is not supported anymore. You need to declare and object array like this:

Person[] persons = given().when().get("person/").as(Person[].class);

for those who found out that accepted answer does not work anymore.

    List<Entity> list = new ArrayList<>();
    list = given()
            .contentType(CONTENT_TYPE)
        .when()
            .get(getRestOperationPath())
        .then()
            .extract().body().as(list.getClass());

hopefully, you understand that getRestOperationPath is returning rest operation path; and CONTENT_TYPE is placeholder for your content type (application/json for example)

upd: checked different versions, behavior differs depending on version, so you might want to try different approaches

upd2: cleaner solution was pointed by @Arigion in comments:

to use .extract().body().jsonPath().getList(".", Entity.class);

To extract a Java List, and not an Array, from a JSON API response, you just have to remember to use jsonPath rather than as:

List<Person> persons = given()
        .when()
        .get("/person")
        .then()
        .extract()
        .body()
        // here's the magic
        .jsonPath().getList(".", Person.class);

Your json path can point to anywhere you expect to have a list of json objects in your body. in this example (and working for your question) it just points to the json root.

sidenode: rest-assured is internally using jackson for deserialization (for .jsonPath as well as .as)


You could also do this if you were interested in using "expect()"

expect().
 body("get(0).firstName", equalTo("Mike")).
when().
 get("person/");

This was my case


If anyone's still looking. Using Java 1.8 and RestAssured 2.9 the solution is really simple and it does not throw "Unchecked Warning".

return Arrays.asList(given()
            .when()
            .get("restPath")
            .then()
            .extract()
            .response()
            .body()
            .as(Player[].class));