Post

Configure the Object Mapper in REST Assured

Choose the object mapper explicitly with ObjectMapperType, see the lenient Jackson 3 default, and plug in your own strict JsonMapper with a Jackson3ObjectMapperFactory, the 6.3 way.

Configure the Object Mapper in REST Assured

The Customers API starts sending a new field, and your contract test, the one meant to notice every change, stays green: Jackson 3 ignores fields the record doesn’t know. Meanwhile a new dependency brings another JSON library onto the classpath, and nobody is sure which mapper the tests now use. In this guide, you’ll choose the object mapper explicitly, see the lenient default for yourself, and plug in a strict Jackson 3 mapper that fails on unknown fields.

Level: Intermediate · Time: 15 minutes · Part of: Module 4: Extracting Values and Mapping Objects, section 4

What You’ll Build

You’ll build a test class called ObjectMapperConfigurationTest with three tests. One names the mapper explicitly; two map the same customer to a record that lacks a field, first with the lenient default and then with a strict mapper that rejects it.

All three tests send this request and map this response:

1
2
3
4
5
6
7
GET /api/v1/customers/cust-1 HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"id":"cust-1","name":"Anna de Vries","email":"anna@example.nl","segment":"RETAIL","createdAt":"..."}

When you’re done, Maven reports three passing tests:

1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Choose the mapper explicitly.
  • See the lenient default.
  • Make the mapper strict.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create ObjectMapperConfigurationTest in a new section_04 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (ObjectMapperConfigurationTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Extract Values From a Response in REST Assured.

Out of scope: this guide doesn’t cover sharing one configuration across a suite, in a request specification or as a static default; that’s taught in Module 5.

Understand Object Mapper Configuration

The problem. Mapping works without configuration because REST Assured finds a mapper on the classpath and uses its defaults. That has two risks. Another library can bring a different mapper onto the classpath, and the defaults may not match what a test is for: Jackson 3 ignores unknown fields, so a test can’t notice when the API adds one.

The concept. REST Assured 6 supports several object mappers: Jackson 3 (package tools.jackson), Jackson 2 (package com.fasterxml.jackson), Gson, JSON-B, Johnzon and, for XML, JAXB. Jackson 3 and Jackson 2 can sit on the classpath side by side, and when several mappers are present, REST Assured prefers Jackson 3. Two things change that:

  • ObjectMapperType names a mapper for one call, such as as(Customer.class, ObjectMapperType.JACKSON_3).
  • ObjectMapperConfig sets the mapper, or a factory that builds it, for every request that uses the config.

When to use each. Name the mapper where it matters, so the test doesn’t depend on the classpath. Keep Jackson 3’s lenient default for everyday tests, which stay focused on the fields they check. Use a strict mapper in a contract test, which should fail on every change in the API, including a new field.

Keep everyday tests lenient, and make contract tests strict.

Meet the API Under Test

The tests read customer cust-1 from the Customers and Consents API:

1
2
3
4
5
6
7
{
    "id": "cust-1",
    "name": "Anna de Vries",
    "email": "anna@example.nl",
    "segment": "RETAIL",
    "createdAt": "2026-11-21T19:19:31.832047Z"
}

Two of the tests map it to a record that has every field except email. That stands for a common situation: the API has added a field that the tests’ records don’t know about yet.

Your tests check two things:

  • The customer’s name, "Anna de Vries", which every successful mapping reads.
  • The unknown email field, which a strict mapper names in its exception.

Choose the Mapper Explicitly

Set Up the Test Class

Goal: create the test class with a record that lacks the email field.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.javanibble.module_04.section_04;

import static io.restassured.RestAssured.given;
import static io.restassured.config.ObjectMapperConfig.objectMapperConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.javanibble.consents.ConsentsApi;
import com.javanibble.module_04.support.Models.Customer;

import io.restassured.common.mapper.factory.Jackson3ObjectMapperFactory;
import io.restassured.config.RestAssuredConfig;
import io.restassured.mapper.ObjectMapperType;
import io.restassured.specification.RequestSpecification;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.json.JsonMapper;

class ObjectMapperConfigurationTest {

    private static ConsentsApi api;

    @BeforeAll
    static void startApi() {
        api = ConsentsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification consentsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(ConsentsApi.BASE_PATH);
    }

    record CustomerWithoutEmail(String id, String name, String segment, java.time.Instant createdAt) {
    }
}

What’s happening:

  • CustomerWithoutEmail is like the record the API should return, but without email. The strict mapper will notice.
  • Jackson3ObjectMapperFactory is imported from io.restassured.common.mapper.factory, the package it moved to in REST Assured 6.3.
  • JsonMapper and DeserializationFeature come from Jackson 3, in the package tools.jackson.databind.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Name the Mapper for One Call

Goal: map a customer with Jackson 3, whatever else is on the classpath.

1
2
3
4
5
6
7
8
@Test
void chooseTheMapperExplicitly() {
    Customer customer = consentsApi()
        .when().get("/customers/{id}", "cust-1")
        .then().extract().as(Customer.class, ObjectMapperType.JACKSON_3);

    assertThat(customer.name()).isEqualTo("Anna de Vries");
}

What’s happening:

  • The second argument to as(..) names the mapper. If a new dependency brings in another one, this call still uses Jackson 3.
  • ObjectMapperType also has JACKSON_2, JACKSON_1, GSON, JAXB, JOHNZON, JSONB and JAKARTA_EE.

Checkpoint: run ObjectMapperConfigurationTest from your IDE. One test runs and passes.

The mapper you name must be on the classpath. This module has only Jackson 3, so as(Customer.class, ObjectMapperType.JACKSON_2) throws IllegalArgumentException: Cannot map response body with mapper JACKSON_2 because jackson_2 doesn't exist in the classpath.

See the Lenient Default

Map to a Record That Lacks a Field

Goal: show that the default mapper ignores a field the record doesn’t have.

1
2
3
4
5
6
7
8
@Test
void aLenientMapperIgnoresFieldsTheRecordLacks() {
    CustomerWithoutEmail customer = consentsApi()
        .when().get("/customers/{id}", "cust-1")
        .then().extract().as(CustomerWithoutEmail.class);

    assertThat(customer.name()).isEqualTo("Anna de Vries");
}

What’s happening:

  • The body has an email field, and CustomerWithoutEmail doesn’t.
  • Jackson 3 ignores it, so the mapping succeeds and the test passes. This is Jackson 3’s default, and the opposite of Jackson 2’s.

Checkpoint: run the class again. Two tests pass.

Make the Mapper Strict

Plug In a Strict JsonMapper

Goal: build a Jackson 3 mapper that fails on unknown fields, and give it to REST Assured for one request.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aStrictMapperFailsOnFieldsTheRecordLacks() {
    JsonMapper strict = JsonMapper.builder()
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .build();
    Jackson3ObjectMapperFactory factory = (type, charset) -> strict;
    RestAssuredConfig strictConfig = config().objectMapperConfig(objectMapperConfig().jackson3ObjectMapperFactory(factory));

    assertThatThrownBy(() -> consentsApi()
            .config(strictConfig)
            .when().get("/customers/{id}", "cust-1")
            .then().extract().as(CustomerWithoutEmail.class))
        .hasStackTraceContaining("email");
}

What’s happening:

  • JsonMapper.builder() builds a Jackson 3 mapper. Jackson 3 mappers are immutable, so every setting goes through the builder; FAIL_ON_UNKNOWN_PROPERTIES makes it strict.
  • Jackson3ObjectMapperFactory tells REST Assured how to get a mapper. It receives the type being mapped and the charset, and here always returns the same strict mapper.
  • objectMapperConfig().jackson3ObjectMapperFactory(..) puts the factory in a RestAssuredConfig, which the request uses through config(..).
  • AssertJ’s assertThatThrownBy(..) expects the mapping to throw, and checks that the stack trace names the field.

The mapping fails with a Jackson exception that names the field and lists the ones the record knows:

1
2
3
tools.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized property "email"
(class ...ObjectMapperConfigurationTest$CustomerWithoutEmail), not marked as ignorable
(4 known properties: "id", "name", "segment", "createdAt")

Checkpoint: run the class again. All three tests pass.

Assign the factory to a variable of the new type before you pass it. REST Assured 6.3 moved the interface to io.restassured.common.mapper.factory; the old one, in io.restassured.path.json.mapper.factory, is deprecated and extends the new one, and jackson3ObjectMapperFactory(..) has an overload for each. A bare lambda, as in jackson3ObjectMapperFactory((type, charset) -> strict), compiles without a warning, but Java picks the most specific overload: the deprecated one. Check the import too, because both interfaces have the same simple name.

Don’t make every test strict. Every new API field would then break tests that don’t care about it. Build the strict config once, for the contract tests, and share it; Module 5 shows how.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-04 -Dtest=ObjectMapperConfigurationTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_04.section_04.ObjectMapperConfigurationTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.209 s -- in com.javanibble.module_04.section_04.ObjectMapperConfigurationTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In aStrictMapperFailsOnFieldsTheRecordLacks, delete the .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) line and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   ObjectMapperConfigurationTest.aStrictMapperFailsOnFieldsTheRecordLacks:83
Expecting code to raise a throwable.

Without the feature, the custom mapper is as lenient as the default, so the mapping succeeds and nothing is thrown. AssertJ reports that the code it expected to fail didn’t. This is the contract test from the opening, staying green while the API changes.

Put the .enable(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
IllegalArgumentException: Cannot map response body with mapper JACKSON_2 because jackson_2 doesn't exist in the classpath.The named mapper isn’t a dependencyName a mapper that’s on the classpath, or add the dependency
UnrecognizedPropertyException: Unrecognized property "..."A strict mapper met a field the record doesn’t haveAdd the component to the record, or use the lenient default
Expecting code to raise a throwable.The custom mapper isn’t strictEnable FAIL_ON_UNKNOWN_PROPERTIES on the builder
Your IDE marks Jackson3ObjectMapperFactory as deprecatedThe import is from io.restassured.path.json.mapper.factoryImport it from io.restassured.common.mapper.factory

Try It Yourself

Exercise 1: Map Only What You Need

Add a record called CustomerName with only id and name, and a test called aSmallRecordWithAnExplicitMapper that maps cust-2 to it with ObjectMapperType.JACKSON_3. Check the status code first, then check the id "cust-2" and the name "Jan Jansen" in one AssertJ statement.

Hint

Declare the record inside the test class, as CustomerWithoutEmail is. The lenient default ignores the three fields the record doesn’t have.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
record CustomerName(String id, String name) {
}

@Test
void aSmallRecordWithAnExplicitMapper() {
    CustomerName customer = consentsApi()
        .when().get("/customers/{id}", "cust-2")
        .then().statusCode(200)
        .extract().as(CustomerName.class, ObjectMapperType.JACKSON_3);

    assertThat(customer)
        .returns("cust-2", CustomerName::id)
        .returns("Jan Jansen", CustomerName::name);
}

Exercise 2: Prove the Strict Mapper Accepts a Complete Record

A strict mapper should reject a record that lacks a field, but accept one that matches the JSON. Add a helper that builds the strict config, and a test called aStrictMapperAcceptsACompleteRecord. With the strict config, map cust-1 to the full Customer record and check its email "anna@example.nl". Then map it to CustomerName from Exercise 1 and check that the stack trace contains Unrecognized property "email".

Hint

Move the three lines that build strictConfig into a private static RestAssuredConfig strictConfig() method, so both requests can use it.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static RestAssuredConfig strictConfig() {
    JsonMapper strict = JsonMapper.builder()
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .build();
    Jackson3ObjectMapperFactory factory = (type, charset) -> strict;
    return config().objectMapperConfig(objectMapperConfig().jackson3ObjectMapperFactory(factory));
}

@Test
void aStrictMapperAcceptsACompleteRecord() {
    Customer customer = consentsApi()
        .config(strictConfig())
        .when().get("/customers/{id}", "cust-1")
        .then().statusCode(200)
        .extract().as(Customer.class);

    assertThat(customer.email()).isEqualTo("anna@example.nl");

    assertThatThrownBy(() -> consentsApi()
            .config(strictConfig())
            .when().get("/customers/{id}", "cust-1")
            .then().extract().as(CustomerName.class))
        .hasStackTraceContaining("Unrecognized property \"email\"");
}

Summary

You built ObjectMapperConfigurationTest, which names the mapper for one call, shows Jackson 3’s lenient default, and plugs in a strict mapper that rejects a field the record doesn’t know. The contract test can now notice a new field in the API.

  • REST Assured 6 supports Jackson 3, Jackson 2, Gson, JSON-B, Johnzon and JAXB, and prefers Jackson 3 when several are present.
  • ObjectMapperType names a mapper for one call; the mapper must be on the classpath.
  • Jackson 3 ignores unknown fields by default, so everyday tests stay focused on the fields they check.
  • A JsonMapper with FAIL_ON_UNKNOWN_PROPERTIES, passed through a Jackson3ObjectMapperFactory in ObjectMapperConfig, makes mapping strict.
  • Since REST Assured 6.3, import the factory from io.restassured.common.mapper.factory and assign it to a typed variable, so the code doesn’t bind to the deprecated interface.

Here are the commands you used in this guide:

1
mvn test -pl module-04 -Dtest=ObjectMapperConfigurationTest

What’s Next

Next: continue with Chain Requests Into an API Flow in REST Assured, which builds the open banking consent flow, from customer to balances, where each step uses what the previous one returned.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.