我正在尝试做的是避免请求中出现空字段。我用这个球衣依赖

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

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

最佳答案

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

07-24 13:22