如何在Spring Boot 1.5.9中全局配置Jackson NON_EMPTY序列化规则
全局配置Jackson的NON_EMPTY序列化规则(Spring Boot 1.5.9 + Jackson 2.8.10)
我之前也碰到过类似的问题,在Spring Boot 1.5.x版本里配置Jackson全局序列化规则确实有几个容易踩的坑,给你几个靠谱的解决方案试试:
方案一:修正application.properties配置
你之前用的spring.jackson.default-property-inclusion=non_null是针对NON_NULL规则的,要实现NON_EMPTY只需要修改配置值即可。不过要注意,Spring Boot 1.5.x对这个配置项的取值严格对应Jackson的Include枚举值,正确配置如下:
spring.jackson.default-property-inclusion=non_empty
⚠️ 注意:如果你的项目中已经存在自定义的ObjectMapper Bean,这个配置会被覆盖,此时需要优先排查配置类的冲突。
方案二:通过配置类定制ObjectMapper
你之前尝试的配置类可能存在遗漏,完整的可生效配置类应该是这样的:
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; @Configuration public class JacksonGlobalConfig { @Primary @Bean public ObjectMapper customObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.build(); // 全局设置序列化规则为NON_EMPTY objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); return objectMapper; } }
这里有几个关键细节:
- 必须添加
@Configuration注解,让Spring识别这是一个配置类 @Primary注解确保这个ObjectMapper是优先被使用的,避免其他自定义的ObjectMapper覆盖全局配置- 通过
Jackson2ObjectMapperBuilder构建实例,能保留Spring Boot默认的Jackson配置(比如日期格式化、模块注册等),只追加我们需要的规则
方案三:排查局部覆盖问题
如果以上方案都不生效,需要检查以下两点:
- 检查实体类是否单独标注了
@JsonInclude注解,局部注解会直接覆盖全局配置,需要移除这些局部设置 - 检查项目中是否存在
WebMvcConfigurerAdapter的实现类,如果重写了configureMessageConverters方法,要确保使用的是我们配置好的ObjectMapper,示例代码如下:
import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { private final ObjectMapper customObjectMapper; // 注入我们配置好的全局ObjectMapper public WebMvcConfig(ObjectMapper customObjectMapper) { this.customObjectMapper = customObjectMapper; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(customObjectMapper); converters.add(0, converter); // 放在最前面确保优先使用 } }
这几个方案应该能解决你的问题,我当时是用第二个方案搞定的,你可以按顺序试试,先改配置文件,不行再用配置类的方式。
内容的提问来源于stack exchange,提问作者AlejoDev
相关产品推荐
相关产品推荐

