【问题标题】:For Spring Boot 1.2.3, how to set ignore null value in JSON serialization?对于 Spring Boot 1.2.3,如何在 JSON 序列化中设置忽略 null 值?
【发布时间】:2015-07-14 13:39:54
【问题描述】:

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

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 spring-boot serialization null jackson


    【解决方案1】:

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

    spring.jackson.default-property-inclusion=non_null

    对于 Jackson 2.7 之前的版本:

    spring.jackson.serialization-inclusion=non_null

    【讨论】:

    • 这仅适用于 Spring Boot 版本 1.3.0
    • 记住不要使用 new RestTemplate() 因为它不会使用这个配置,而是创建默认转换器。 RestTemplateBuilder.build() 使用所有配置
    • @cjungel,我已经尝试过这个解决方案,但对我不起作用,我使用的是 1.5.7 版本的 spring boot
    • 我正在使用1.5.10.RELEASE 版本,它对我来说就像魅力一样。
    【解决方案2】:

    在弃用之前这是一个很好的解决方案: @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

    【讨论】:

    • 看起来枚举 com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion 在 jackson-databind 的 2.6 版中已弃用
    【解决方案3】:

    对于 Spring Boot 1.4.x,您可以在 application.properties 中包含以下行

    spring.jackson.default-property-inclusion=non_null

    【讨论】:

      【解决方案4】:

      这是 Spring Boot 1.3.0 的增强功能。

      所以很遗憾,您需要在 1.2.3 上以编程方式对其进行配置

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

      【讨论】:

      • 非常感谢,非常有帮助。
      • 它说包含已弃用
      • 此包含已弃用。相反,@JsonInclude(JsonInclude.Include.NON_NULL) 需要按照以下答案中的说明使用
      【解决方案5】:

      类范围,

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

      物业范围:

      public class MyModel {   
          .....
      
          @JsonInclude(JsonInclude.Include.NON_NULL)
          private String myProperty;
      
          .....
      }
      

      【讨论】:

        【解决方案6】:
          @Bean
          public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
            return mapperBuilder.build().setSerializationInclusion(Include.NON_NULL);
          }
        

        对我有用

        【讨论】:

        • 这对我来说是正确的解决方案,因为我不想在我的共享对象类中添加注释
        猜你喜欢
        • 1970-01-01
        • 2014-09-11
        • 2015-02-24
        • 2013-04-11
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        相关资源
        最近更新 更多