How do I access the underlying Jackson ObjectMapper in REST Assured?

Given the context for which Rest Assured is used, often times you'll want to modify or provide the ObjectMapper used for some request, but not all of them.

You can achieve this by using the methods:

  • .body(Object object, ObjectMapper mapper) or .content(Object object, ObjectMapper mapper)(deprecated in favor of .body()), to serialize your request body/payload.
  • .as(Type cls, ObjectMapper mapper) or .as(Class<T> cls, ObjectMapper mapper), to deserialize your request's response body.

A classic use case, as @jason-henriksen mentioned is to

  • Allow unknown properties to be ignored
  • Ignore properties defined in your ReturnedType class that are not marked with @JsonIgnore without throwing an Exception during the deserialization (useful when you have no control/ can't modify that ReturnedType class 1)

This can be done with:

RequestSpecification request = ...;
io.restassured.mapper.ObjectMapper objectMapper = new Jackson2Mapper(((type, charset) -> {
    com.fasterxml.jackson.databind.ObjectMapper om = new ObjectMapper().findAndRegisterModules();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return om;
}));
ReturnType response = request.get().as(ReturnType.class, objectMapper);

1 You can also achieve this by configuring your ObjectMapper with Jackson MixIns.


This will give you an object mapper that does not explode when the back end developer decides to add a new field.

RestAssured.config = RestAssuredConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
    new Jackson2ObjectMapperFactory() {
      @Override
      public ObjectMapper create(Type cls, String charset) {
        ObjectMapper om = new ObjectMapper().findAndRegisterModules();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return om;
      }          

    }
));

You can try this:

RestAssured.config = RestAssuredConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
new Jackson2ObjectMapperFactory() {
        @Override
        public ObjectMapper create(Class aClass, String s) {
            FilterProvider filter = new SimpleFilterProvider().addFilter(...);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setFilters(filter);
            return objectMapper;
        }
    }
));

@sanj's answer was very helpful. I had to modify it slightly because I'm using RestAssuredMockMvc.

This is how I configure RestAssuredMockMvc to use snake_case instead of CamelCase:

RestAssuredMockMvc.config = RestAssuredMockMvcConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
            (type, s) -> {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
                return objectMapper;
            }
    ));