REST Assured - Generic List deserialization

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)


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);

We can now use TypeRef much as it's possible to do it with the JsonPath library:

List<Person> persons = given().when().get("person/")
    .as(new TypeRef<List<Person>>() {});

As with https://github.com/json-path/JsonPath#what-is-returned-when - the anonymous inner class new TypeRef<List<Person>>() {} gets around type erasure and captures the type information enough that the framework can access the raw type - List in this case. The internal generic type - Person - is a safe cast that can be made under the circumstances.