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

前端 未结 6 1955

In the Spring Boot 1.2.3, we can customize the Jackson ObjectMapper via properties file. But I didn\'t find a attribute can set Jackson ignore null value when serialization

相关标签:
6条回答
  • 2020-12-18 18:57

    Class-wide,

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

    Property-wide:

    public class MyModel {   
        .....
    
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String myProperty;
    
        .....
    }
    
    0 讨论(0)
  • 2020-12-18 19:04

    Add the following line to your application.properties file.

    spring.jackson.default-property-inclusion=non_null

    For versions of Jackson prior to 2.7:

    spring.jackson.serialization-inclusion=non_null

    0 讨论(0)
  • 2020-12-18 19:06

    This was a good solution before deprecation: @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

    But now you should use:

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

    You can take a look here: https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html

    0 讨论(0)
  • 2020-12-18 19:07

    For Spring Boot 1.4.x, you can include the following line to your application.properties

    spring.jackson.default-property-inclusion=non_null

    0 讨论(0)
  • 2020-12-18 19:07
      @Bean
      public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
        return mapperBuilder.build().setSerializationInclusion(Include.NON_NULL);
      }
    

    that works for me

    0 讨论(0)
  • 2020-12-18 19:09

    This was an enhancement for Spring Boot 1.3.0.

    • Support for spring.jackson.include
    • Add properties for Jackson serializationInclusion

    So unfortunately you'll need to configure it programmatically on 1.2.3

    @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
    public class Shop {
        //...
    }
    
    0 讨论(0)
提交回复
热议问题