Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Jackson in spring boot application without overriding springs default setting in pure java

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.

like image 777
dermoritz Avatar asked Jan 30 '18 10:01

dermoritz


People also ask

Does spring use Jackson by default?

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.

What is Spring Jackson default property inclusion?

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.

Why do we use Jackson in spring boot?

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.


1 Answers

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(...)      
            };
        }
    }
}
like image 79
pvpkiran Avatar answered Sep 20 '22 08:09

pvpkiran