15

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.

Markus Pscheidt
  • 6,853
  • 5
  • 55
  • 76
dermoritz
  • 12,519
  • 25
  • 97
  • 185

2 Answers2

25

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(...)      
            };
        }
    }
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    Thanks. But how to configure "features like DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES MapperFeature.DEFAULT_VIEW_INCLUSION in general? I saw many convenient methods on jackson2ObjectMapperBuilder but does this cover all? – dermoritz Jan 30 '18 at 12:28
  • just edited your post - with nearly the same :-) - thanks – dermoritz Jan 30 '18 at 12:38
5

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
KevinC
  • 306
  • 2
  • 6