2017-07-31 70 views
0

我正在使用Spring Boot 1.5.4版本。我正在使用spring-ws getWebServiceTemplate()進行web服務調用。 SOAP響應對這些字段有很多空值。Spring Boot 1.5.4在json響應中篩選出空值

我想過濾掉JSON響應中的空值。以下方法無似乎工作:

  1. application.properties設置屬性:
spring.jackson.default-property-inclusion:NON_NULL` 
  • 在配置類設置它使用Jackson2ObjectMapperBuilder
  • @Bean 
        public Jackson2ObjectMapperBuilder objectMapperBuilder() { 
         Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();   
         builder.serializationInclusion(JsonInclude.Include.NON_NULL); 
         builder.serializationInclusion(JsonInclude.Include.NON_EMPTY); 
         return builder; 
        } 
    

    請指教。

    LVA

    回答

    1

    我使用Spring引導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); 
          } 
         } 
        } 
    } 
    
    +0

    請提供一些說明關於如何解決問題的答案。這也將有助於避免將來出現同樣的問題。僅有代碼的答案不被高度讚賞。 –