我有一个 REST 服务的返回类型,其中包含一个 Long 字段。当该字段为 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 类调用它。
如何为所有类型调用自定义消息正文编写器?
最佳答案
如果您的 Controller 返回 Long 值,则将使用您的 NullableLongWriter。它不用于序列化 Employee 类的长字段。
但是您可以使用 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>
这相当难看。为什么您不接受评级元素不在 XML 中?
关于java - 未调用 Long 数据类型的自定义 MessageBodyWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436932/