如何在Jersey中从我的JSON请求中排除空字段? [英] How can I exclude null fields form my JSON request in Jersey?

查看:127
本文介绍了如何在Jersey中从我的JSON请求中排除空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是避免请求中的空字段。我使用这种Jersey依赖项

What I'm trying to do is to avoid null fields in my request. I use this Jersey dependencies

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

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

How can I exclude all null fields form my request?

推荐答案

我相信,那是球衣正在使用千斤顶用于序列化。要从序列化的json中排除空字段,请尝试使用 @JsonInclude(Include.NON_NULL)注释目标类。如这个帖子。

I beleive, that jersey is using jackson for serialization. For excluding null fields from serialized json, try to annotate the target class with @JsonInclude(Include.NON_NULL). As explained in this post.

如果无法更改实体,则必须配置自定义ObjectMapper:

If you can't change entities, you must configure your custom 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
    }
}

然后将您的自定义提供商注册到客户端:

then register your custom provider to the client:

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

描述这里

这篇关于如何在Jersey中从我的JSON请求中排除空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆