如何在Jersey中从我的JSON请求中排除空字段?

时间:2014-09-21 14:51:19

标签: java jersey

我尝试做的是避免请求中的空字段。我使用这个Jersey依赖

    <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",
            }
        }
    }

如何从我的请求中排除所有空字段?

2 个答案:

答案 0 :(得分:6)

我相信,那件球衣正在使用杰克逊进行序列化。要从序列化的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

答案 1 :(得分:0)

Jersey 1.x 的替代方案:

org.codehaus.jackson.map.ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Inclusion.NON_NULL);