Q13 of 40 · REST Assured

How do you deserialise a JSON response into a POJO with REST Assured?

REST AssuredMidrest-assuredpojodeserialisationjacksonapi-testing

Short answer

Short answer: Call .extract().as(MyClass.class) at the end of the assertion chain — REST Assured uses Jackson (or Gson) to map the JSON to the POJO automatically. For generic types like List<User>, use .extract().as(new TypeRef<List<User>>(){}). Jackson annotations on the class control field mapping.

Detail

REST Assured detects Jackson or Gson on the classpath and uses it for deserialisation. As long as jackson-databind is a dependency, .extract().as(User.class) just works:

User user = given(reqSpec)
    .when().get("/users/1")
    .then().statusCode(200)
    .extract().as(User.class);

assertThat(user.getEmail()).contains("@");

For generic types, use TypeRef to preserve the type parameter:

List<User> users = given(reqSpec)
    .when().get("/users")
    .then().statusCode(200)
    .extract().as(new TypeRef<List<User>>() {});

Jackson annotations are respected: @JsonProperty("first_name") maps snake_case JSON to camelCase fields. Configure the ObjectMapper globally with RestAssured.config = RestAssuredConfig.config().objectMapperConfig(...) if you need custom settings (dates, null handling).

Trade-off: POJO deserialisation is useful when you need to pass the response to downstream code or run complex Java assertions. For in-chain assertions, .body("field", matcher) is simpler and doesn't require a POJO class.

// EXAMPLE

UserDeserialiseTest.java

// User.java
public class User {
    private int id;
    @JsonProperty("full_name")
    private String fullName;
    private String email;
    // getters/setters omitted
}

// Test
@Test
void getUser_deserialisesToPojo() {
    User user = given(reqSpec)
        .pathParam("id", 1)
    .when()
        .get("/users/{id}")
    .then()
        .statusCode(200)
        .extract().as(User.class);

    assertAll(
        () -> assertThat(user.getId()).isEqualTo(1),
        () -> assertThat(user.getEmail()).endsWith("@example.com"),
        () -> assertThat(user.getFullName()).isNotBlank()
    );
}

// WHAT INTERVIEWERS LOOK FOR

Correct use of .extract().as(), awareness of TypeRef for generic types, and knowing that Jackson annotations are respected. Bonus: mentioning when NOT to use POJO deserialisation (simple assertion-only tests are cleaner with .body() chains).

// COMMON PITFALL

Forgetting TypeRef for List<T> and using List.class instead — this produces a List<LinkedHashMap> at runtime, not List<User>, causing ClassCastExceptions when you access elements.