Configuring ObjectMapper in Spring

前端 未结 12 1697
迷失自我
迷失自我 2020-11-22 10:46

my goal is to configure the objectMapper in the way that it only serialises element which are annotated with @JsonProperty.

In order to do

12条回答
  •  清酒与你
    2020-11-22 11:21

    SOLUTION 1

    First working solution (tested) useful especially when using @EnableWebMvc:

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
        @Autowired
        private ObjectMapper objectMapper;// created elsewhere
        @Override
        public void extendMessageConverters(List> converters) {
            // this won't add a 2nd MappingJackson2HttpMessageConverter 
            // as the SOLUTION 2 is doing but also might seem complicated
            converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
                // check default included objectMapper._registeredModuleTypes,
                // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
                // without Jackson2ObjectMapperBuilder
                ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
            });
        }
    

    SOLUTION 2

    Of course the common approach below works too (also working with @EnableWebMvc):

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
        @Autowired
        private ObjectMapper objectMapper;// created elsewhere
        @Override
        public void extendMessageConverters(List> converters) {
            // this will add a 2nd MappingJackson2HttpMessageConverter 
            // (additional to the default one) but will work and you 
            // won't lose the default converters as you'll do when overwriting
            // configureMessageConverters(List> converters)
            // 
            // you still have to check default included
            // objectMapper._registeredModuleTypes, e.g.
            // Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
        }
    

    Why @EnableWebMvc usage is a problem?

    @EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

    if (jackson2Present) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
        if (this.applicationContext != null) {
            builder.applicationContext(this.applicationContext);
        }
        messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
    

    which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

提交回复
热议问题