【问题标题】:How to ignore "null" or empty properties in json, globally, using Spring configuration如何使用 Spring 配置全局忽略 json 中的“null”或空属性
【发布时间】:2016-12-14 04:32:21
【问题描述】:

我试图只返回具有值的属性,但也返回空值。

我知道有一个注释可以做到这一点(@JsonInclude(Include.NON_NULL)),但是我在每个实体类中都需要这些。

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

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

【问题讨论】:

    标签: java json spring spring-mvc jackson


    【解决方案1】:

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

    spring.jackson.serialization-inclusion=non_null
    

    如果没有,那么您可以像这样在 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);
                }
            }
        }
    }
    

    【讨论】:

    • 看来您需要在较新的 Spring Boot (1.5.2) 中使用 'spring.jackson.default-property-inclusion = non_null'
    • @DavidTinker 的属性在 Spring Boot 2.25 中对我不起作用,而 Java 手动配置起作用
    【解决方案2】:

    如果您使用 jackson ObjectMapper 生成 json,您可以为此目的定义以下自定义 ObjectMapper 并改为使用它:

    <bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
       <property name="serializationInclusion">
          <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
       </property>
    </bean>
    

    【讨论】:

      【解决方案3】:

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

      spring.jackson.default-property-inclusion=non_null
      

      【讨论】:

        【解决方案4】:

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

        /**
         * Jackson configuration class.
         */
        @Configuration
        public class JacksonConfig {
        
            @Bean
            public ObjectMapper buildObjectMapper() {
               return new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
            }
        }
        

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

        另一个替代方案,根据 Spring Boot documentation,对于 Jackson 2+,是在 application.properties 中配置它:

        spring.jackson.default-property-inclusion=non_null
        

        【讨论】:

          猜你喜欢
          • 2012-12-29
          • 1970-01-01
          • 2017-09-21
          • 2016-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-03
          • 1970-01-01
          相关资源
          最近更新 更多