@JsonInclude(Include.NON_NULL)全局配置

官方文档 跳转

1、springMVC.xml

<!-- 默认的注解映射的支持 比如requestMapper之类的 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion"> 
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value> 
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

  

2、spring boot 的配置

配置文件加上:

spring.jackson.default-property-inclusion=non_null

  

或者:

 1 @Configuration
 2 @EnableWebMvc
 3 @Slf4j
 4 public class WebMvcConfig extends WebMvcConfigurerAdapter {
 5    
 6     //@JsonInclude(Include.NON_NULL)全局配置
 7     @Override
 8     public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
 9         Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
10                 .serializationInclusion(JsonInclude.Include.NON_NULL);
11         converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
12     }
13 }
【微信公众号:Stephen】一个毕业三年后自学 Java 入行的程序员。
原文地址:https://www.cnblogs.com/stephen-java/p/11377669.html