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

2024-01-12

我想要做的是避免请求中出现空字段。我使用这个 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",
            }
        }
    }

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


我相信,该球衣正在使用杰克逊进行序列化。要从序列化 json 中排除空字段,请尝试使用以下方法注释目标类@JsonInclude(Include.NON_NULL)。正如中所解释的this https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null post.

如果您无法更改实体,则必须配置自定义 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 https://jersey.github.io/documentation/latest/media.html#json.jackson

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Jersey 中排除 JSON 请求中的空字段? 的相关文章

随机推荐