Question
I've been unable to find examples of how to use Jackson2ObjectMapperBuilderCustomizer.java in spring boot 1.4 to customise the features of Jackson.
The doco for customising Jackson in boot 1.4 - <https://docs.spring.io/spring- boot/docs/1.4.x/reference/htmlsingle/#howto-customize-the-jackson- objectmapper>
My configuration works, although I am unsure if this is the correct way to customise the object mapper using Jackson2ObjectMapperBuilderCustomizer.java
@Configuration
public class JacksonAutoConfiguration {
@Autowired
private Environment env;
@Bean
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = configureObjectMapper();
customize(builder, customizers);
return builder;
}
private void customize(Jackson2ObjectMapperBuilder builder,
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) {
customizer.customize(builder);
}
}
private Jackson2ObjectMapperBuilder configureObjectMapper() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
List<String> activeProfiles = asList(env.getActiveProfiles());
if (activeProfiles.contains(SPRING_PROFILE_DEVELOPMENT)) {
builder.featuresToEnable(SerializationFeature.INDENT_OUTPUT);
}
return builder;
}
}
To provide some context, this class sits in my own spring starter project for REST services that just auto configures a number of things, like ControllerAdvice and some trivial features like the above.
So my goal is to extend the Jackson configuration rather than to override any configuration provided by boot or other packages.
Answer
To customize the Jackson ObjectMapper
that's already pre-configured by
Spring Boot, I was able to do this (the example here is to add a custom
deserializer).
Configuration class:
@SpringBootConfiguration
public class Application {
@Autowired
private BigDecimalDeserializer bigDecimalDeserializer;
...
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.deserializerByType(BigDecimal.class, bigDecimalDeserializer);
}
};
}
...
}
And my custom deserializer, to show how it's picked up by Spring:
@Component
public class BigDecimalDeserializer extends StdDeserializer<BigDecimal> {
public BigDecimalDeserializer() {
super(BigDecimal.class);
}
@Override
public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
...
}
...
}