对于Spring Boot 1.2.3,如何在JSON序列化中设置忽略空值?

For Spring Boot 1.2.3, how to set ignore null value in JSON serialization?

在Spring Boot 1.2.3中,我们可以通过属性文件自定义Jackson ObjectMapper。但是我没有找到一个属性可以在将对象序列化为 JSON 字符串时设置 Jackson 忽略空值。

spring.jackson.deserialization.*= # see Jackson's DeserializationFeature
spring.jackson.generator.*= # see Jackson's JsonGenerator.Feature
spring.jackson.mapper.*= # see Jackson's MapperFeature
spring.jackson.parser.*= # see Jackson's JsonParser.Feature
spring.jackson.serialization.*=

我想归档与

相同的代码
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);

这是 Spring Boot 1.3.0 的增强功能。

很遗憾,您需要在 1.2.3 上以编程方式配置它

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Shop {
    //...
}

将以下行添加到您的 application.properties 文件中。

spring.jackson.default-property-inclusion=non_null

对于 2.7 之前的 Jackson 版本:

spring.jackson.serialization-inclusion=non_null

对于 Spring 引导 1.4.x,您可以将以下行添加到您的 application.properties

spring.jackson.default-property-inclusion=non_null

在弃用之前这是一个很好的解决方案: @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

但现在你应该使用:

@JsonInclude(JsonInclude.Include.NON_NULL) public class ClassName { ...

你可以看这里: https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html

Class-wide,

@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyModel { .... }

Property-wide:

public class MyModel {   
    .....

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String myProperty;

    .....
}
  @Bean
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
    return mapperBuilder.build().setSerializationInclusion(Include.NON_NULL);
  }

适合我