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.
Spring Framework and Spring Boot provide builtin support for Jackson based XML serialization/deserialization. As soon as you include the jackson-dataformat-xml dependency to your project, it is automatically used instead of JAXB2.
Besides the mentioned feature categories, we can also configure property inclusion: spring.jackson.default-property-inclusion=always, non_null, non_absent, non_default, non_empty. Configuring the environment variables in the simplest approach.
Springboot automatically configures jackson message converters for rest endpoints if it finds jackson as dependency or classpath.So all you need to enable a rest endpoint to return a json response is to have the jackson as dependency and springboot will take care of the rest through autoconfiguration.
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(...)
};
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With