如何使用Spring配置全局忽略json中的"null"或空属性

Ped*_*lva 9 java spring json spring-mvc jackson

我试图只返回具有值的属性,但也返回null.

我知道有一个注释可以执行this(@JsonInclude(Include.NON_NULL)),但是我需要在每个实体类中使用它们.

所以,我的问题是:有没有办法通过spring配置全局配置?(最好避免使用XML)

编辑:似乎这个问题被认为是重复的,但我不这么认为.这里真正的问题是如何通过spring配置来配置它,这是我在其他问题中找不到的.

Jon*_*son 17

如果您使用的是Spring Boot,这很简单:

spring.jackson.serialization-inclusion=non_null
Run Code Online (Sandbox Code Playgroud)

如果没有,那么您可以在MappingJackson2HttpMessageConverter中配置ObjectMapper,如下所示:

@Configuration
class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for(HttpMessageConverter converter: converters) {
            if(converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper mapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper()
                mapper.setSerializationInclusion(Include.NON_NULL);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 看来你需要在更新的Spring Boot(1.5.2)中使用'spring.jackson.default-property-inclusion = non_null' (12认同)

JRA*_*TLL 7

在较新版本的 Spring Boot (2.0+) 中,使用:

spring.jackson.default-property-inclusion=non_null
Run Code Online (Sandbox Code Playgroud)


ari*_*iro 6

Abolfazl Hashemi答案的程序化替代方案如下:

/**
 * Jackson configuration class.
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper buildObjectMapper() {
       return new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您基本上就告诉 Spring 容器,每次ObjectMapper使用 an 时,只有具有非空值的属性才会包含在映射中。

根据Spring Boot 文档,对于 Jackson 2+,另一种选择是在以下位置进行配置application.properties

spring.jackson.default-property-inclusion=non_null
Run Code Online (Sandbox Code Playgroud)

编辑:

如果,而不是application.properties依赖application.yml,则应使用以下配置:

spring:
    jackson:
        default-property-inclusion: non_null
Run Code Online (Sandbox Code Playgroud)