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