我有一个REST服务的返回类型,它包含一个长字段。当该字段为NULL时,返回的XML将跳过该字段。我希望该字段出现在输出中,作为一个空元素。
例如:如果POJO定义如下:
class Employee
{
String name;
Integer rating;
}
返回的XML为
<root><employee><name>John</name></employee></root>
而我想要的是:
<root><employee><name>John</name><rating></rating></employee></root>
为了做到这一点,我按照http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-MessageBodyProviders中的说明编写了一个自定义的messagebodywriter
@Produces("text/plain")
public class NullableLongWriter implements MessageBodyWriter<Long> {
public long getSize(Long l, Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
return -1;
}
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
return long.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type);
}
public void writeTo(Long l, Class<?> clazz, Type type, Annotation[] a,
MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
throws IOException
{
if (l == null)
os.write("".toString().getBytes());
else
os.write(l.toString().getBytes());
}
}
但它不是为Long类型调用的。它只为Employee类调用。
如何为所有类型调用自定义messagebodywriter?
发布于 2015-07-15 18:54:00
如果您的控制器将返回一个长值,则将使用您的NullableLongWriter。它不用于序列化Employee类的long字段。
但是您可以使用JAXB注释影响Pojo的XML序列化:
@XmlAccessorType(XmlAccessType.FIELD)
class Employee
{
String name;
@XmlElement(nillable=true)
Integer rating;
}
您的示例将被序列化为
<employee>
<name>John</name>
<rating xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</employee>
这是相当丑陋的。为什么不接受rating元素不在XML中呢?
https://stackoverflow.com/questions/31436932
复制