Reputation: 13001
In my spring boot application i am using Jackson to serialize objects by injecting the ObjectMapper
where needed.
I found this answer: https://stackoverflow.com/a/32842962/447426
But this one creates a new mapper - with jacksons default settings.
On the other hand i found this in official docu. I didn't really understand. There is no example code.
So how to configure springs ObjectMapper on base of Spring's default object mapper?
This configuration should be active on "ObjectMapper" whereever injected.
Upvotes: 15
Views: 17678
Reputation: 27018
You should use Jackson2ObjectMapperBuilderCustomizer
for this
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Add your customization
// jacksonObjectMapperBuilder.featuresToEnable(...)
}
};
}
}
Because a Jackson2ObjectMapperBuilderCustomizer
is a functor, Java 8 enables more compact code:
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return builder -> {
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Add your customization
// builder.featuresToEnable(...)
};
}
}
}
Upvotes: 27
Reputation: 335
On the other hand i found this in official docu. I didn't really understood. There is no example code.
It's just saying that you only need to set the correct properties in the application.properties
file to enable or disable the various Jackson features.
spring.jackson.mapper.default-view-inclusion=false
spring.jackson.deserialization.fail-on-unknown-properties=false
Upvotes: 5