javaspringspring-bootjackson

How do I set Jackson's constructorDetector with Spring Boot?


I want to configure Jackson so that it automatically deserializes using constructors, without needing annotations. With Spring Boot, this works out of the box for most constructors but not single argument constructors.

Jackson 2.12 has released a configuration option to enable deserialization for single argument constructors as well:

ObjectMapper mapper = JsonMapper.builder()
    .constructorDetector(ConstructorDetector.USE_PROPERTIES_BASED)
    .build()

However, this doesn't use the usual Feature enabling/disabling interface. How can I set this with Spring Boot?

  1. I don't want to lose any Spring Boot autoconfiguration that is being applied to the ObjectMapper bean.
  2. I can't define a Jackson2ObjectMapperBuilder bean because, as of Spring Boot 2.4.1, this has not yet been updated to allow constructorDetector to be set.

Solution

  • Defining a bean of either Jackson2ObjectMapperBuilder or ObjectMapper will prevent application of any auto-configuration for these beans, as documented.

    Instead, you can define a bean of type Jackson2ObjectMapperBuilderCustomizer which is a lambda that lets you call additional methods on the Spring Boot auto-configured Jackson2ObjectMapperBuilder.

    Additionally, Jackson2ObjectMapperBuilder has the method postConfigurer which is another call back which lets you call methods on the auto-configured ObjectMapper.

    Putting these together:

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.postConfigurer(mapper ->
                mapper.setConstructorDetector(USE_PROPERTIES_BASED)
        );
    }