2014-09-21 22 views
2

我想要做的是避免我的請求中的空字段。我用這個州的依賴如何從Jersey中排除我的JSON請求中的空字段?

<dependency> 
     <groupId>org.glassfish.jersey.core</groupId> 
     <artifactId>jersey-client</artifactId> 
     <version>2.5</version> 
    </dependency> 
    <dependency> 
     <groupId>com.sun.jersey</groupId> 
     <artifactId>jersey-json</artifactId> 
     <version>1.18</version> 
    </dependency> 
    <dependency> 
     <groupId>com.sun.jersey.contribs</groupId> 
     <artifactId>jersey-multipart</artifactId> 
     <version>1.17</version> 
    </dependency> 
    <dependency> 
     <groupId>org.glassfish.jersey.media</groupId> 
     <artifactId>jersey-media-json-jackson</artifactId> 
     <version>2.5.1</version> 
    </dependency> 

這裏是我的球衣配置

Client client = ClientBuilder 
     .newClient() 
     .register(authenticationFeature) 
     .register(CustomTypeProvider.class) 
     .register(MultiPartWriter.class) 
     .register(JacksonFeature.class); 

而這正是我想要送

{ 
    "locale": "en_US", 
    "file": { 
     "file": { 
      "version": null, 
      "permissionMask": null, 
      "creationDate": null, 
      "updateDate": null, 
      "label": "my.properties", 
      "description": null, 
      "uri": null, 
      "type": "prop", 
      "content": null 
     } 
    } 
} 

,但我需要

{ 
     "locale": "en_US", 
     "file": { 
      "file": { 
       "label": "my.properties", 
       "type": "prop", 
      } 
     } 
    } 

我如何排除所有空fi領域形成我的要求?

+0

第一所有,不要混合版本! – zyexal 2014-09-21 15:11:16

回答

5

我相信,這件球衣正在使用傑克遜進行系列化。要從序列化的json中排除空字段,請嘗試使用@JsonInclude(Include.NON_NULL)註釋目標類。正如this後所述。

如果你不能改變的實體,您必須配置您的自定義ObjectMapper:

@Provider 
public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { 

    final ObjectMapper mapper; 

    public MyObjectMapperProvider() { 
     mapper = new ObjectMapper(); 
     mapper.setSerializationInclusion(Include.NON_NULL); 
    } 

    @Override 
    public ObjectMapper getContext(Class<?> type) { 
     return mapper 
    } 
} 

然後註冊自定義提供給客戶端:

Client client = ClientBuilder 
    .newClient() 
    .register(MyObjectMapperProvider.class) 
    .register(JacksonFeature.class); 

其描述here

+0

但我無法更改實體。所有的設置都必須在澤西島執行。 – Alex 2014-09-21 15:03:59

+1

然後你需要通過mapper.setSerializationInclusion(Include.NON_NULL);'直接配置你的ObjectMapper。這裏是一個解釋如何爲球衣做到這一點:http://wiki.fasterxml.com/JacksonFAQJaxRs。您需要編寫自定義的ContextResolver,它將提供您的微調ObjectMapper。然後將其註冊到您示例中的客戶端實例 – 2014-09-21 23:03:54

相關問題