我想要做的是避免我的请求中的空字段.我使用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帖子中所解释的那样.
如果无法更改实体,则必须配置自定义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