Jersey POJOMappingFeature将null转换为空字符串? [英] Jersey POJOMappingFeature to convert null to empty string?
问题描述
我正在使用Jersey 1.18,并且启用了POJOMappingFeature.
我希望所有传入的&将要从null
转换为空字符串的传出JSON值.
I'm using Jersey 1.18 and I have POJOMappingFeature enabled.
I would like all incoming & outgoing JSON values to be converted from null
to an empty string.
如何配置映射? 我已经搜索过网络,但是找不到我想要的东西.
How to configure the mapping? I've searched web but was unable to find what I'm looking for.
来自我的web.xml:
from my web.xml:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.abc.restControllers</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
和控制器示例:
package com.abc.restControllers;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.abc.restModals.Place.Place_descInfo_Request;
import com.abc.restModals.Place.Place_descInfo_Response;
@Path("/place")
public class PlaceController {
@POST
@Path("/place_descInfo")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Place_descInfo_Response place_descInfo(Place_descInfo_Request req) {
return new Place_descInfo_Response(req);
}
} // End class
推荐答案
如果您使用的是杰克逊 ,您可以为pojos编写自定义序列化程序.例如:
If you are using Jackson, you can write a custom serializer for your pojos. For instance:
public class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize(final Foo value, final JsonGenerator jgen,
final SerializerProvider provider) throws IOException
{
if (value.bar() == null) {
jgen.writeString("");
} else {
jgen.writeString(value.bar());
}
}
}
然后,在您的Foo
对象上:
@JsonSerialize(using = FooSerializer.class)
public class Foo {
private String bar;
public String bar() {
return bar;
}
}
您还可以通过扩展JsonDeserializer
来处理传入的空值来创建自定义反序列化器,或者放置一个过滤器以解析主体?
You can also create custom deserializers by extending JsonDeserializer
to handle incoming nulls, or put a filter in place to parse the body?
这篇关于Jersey POJOMappingFeature将null转换为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!