Spring Boot 1.5.4在json响应中过滤掉空值

时间:2017-07-31 18:47:48

标签: spring-boot null

我正在使用Spring Boot 1.5.4版本。我正在使用spring-ws getWebServiceTemplate()进行网络服务调用。 SOAP响应有很多字段的空值。

我正在尝试过滤掉JSON响应中的空值。以下方法似乎都不起作用:

  1. application.properties
  2. 中设置属性
    spring.jackson.default-property-inclusion:NON_NULL`
    
    1. 使用Jackson2ObjectMapperBuilder
    2. 在Configuration类中进行设置
      @Bean
          public Jackson2ObjectMapperBuilder objectMapperBuilder() {
              Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();        
              builder.serializationInclusion(JsonInclude.Include.NON_NULL);
              builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
              return builder;
          } 
      

      请告知。

      LVA

2 个答案:

答案 0 :(得分:2)

我使用的是Spring Boot 1.5.6.RELEASE版本,您可以参考 customize-the-jackson-objectmapper

以下代码可行:

 @SpringBootApplication
    public class Application {

        @Bean
        public Jackson2ObjectMapperBuilder objectMapperBuilder() {
            Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
            builder.serializationInclusion(JsonInclude.Include.NON_NULL);
            return builder;
        }

        public static void main(String[] args) {
            SpringApplication.run(DbeeApiApplication.class, args);
        }
    }

或者您可以从MappingJackson2HttpMessageConverter进行过滤,例如:

@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);
            }
        }
    }
}

答案 1 :(得分:0)

在application.properties中使用以下内容有效。

spring.jackson.default-property-inclusion=NON_NULL