Spring REST Service: how to configure to remove null objects in json response

前端 未结 10 1242
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 07:06

I have a spring webservice that returns a json response. I\'m using the example given here to create the service: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-exam

10条回答
  •  一向
    一向 (楼主)
    2020-11-28 07:55

    Setting the spring.jackson.default-property-inclusion=non_null option is the simplest solution and it works well.

    However, be careful if you implement WebMvcConfigurer somewhere in your code, then the property solution will not work and you will have to setup NON_NULL serialization in the code as the following:

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
        // some of your config here...
    
        @Override
        public void configureMessageConverters(List> converters) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
            converters.add(jsonConverter);
        }
    }
    

提交回复
热议问题