Java 未调用长数据类型的自定义MessageBodyWriter
我有一个REST服务的返回类型,它包含一个长字段。当该字段为空时,返回的XML将跳过该字段。我希望字段作为空元素出现在输出中 例如:如果POJO定义如下:Java 未调用长数据类型的自定义MessageBodyWriter,java,rest,cxf,Java,Rest,Cxf,我有一个REST服务的返回类型,它包含一个长字段。当该字段为空时,返回的XML将跳过该字段。我希望字段作为空元素出现在输出中 例如:如果POJO定义如下: class Employee { String name; Integer rating; } 返回的XML是 <root><employee><name>John</name></employee></root> 约翰 鉴于我希望它是: <root&
class Employee
{
String name;
Integer rating;
}
返回的XML是
<root><employee><name>John</name></employee></root>
约翰
鉴于我希望它是:
<root><employee><name>John</name><rating></rating></employee></root>
约翰
为此,我按照中的说明编写了一个自定义messagebodywriter
@产生(“文本/普通”)
公共类NullableLongWriter实现MessageBodyWriter{
公共长getSize(长l、类类型、类型genericType、注释[]注释、MediaType mt){
返回-1;
}
公共布尔值可写(类类型、类型genericType、注释[]注释、MediaType mt){
返回long.class.isAssignableFrom(type)| long.class.isAssignableFrom(type);
}
公共无效写入(长l,类类别,类型,注释[]a,
MediaType mt、多值映射头、OutputStream os)
抛出IOException
{
if(l==null)
write(“.toString().getBytes());
其他的
write(l.toString().getBytes());
}
}
但它并不是长型的。它只为Employee类调用
如何为所有类型调用自定义messagebodywriter?如果控制器返回长值,则将使用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>
约翰
这相当难看。为什么不接受rating元素不在XML中?如果控制器返回一个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中没有评级元素?谢谢!我在客户端使用beautifulsoup解析xml,并希望其中包含空元素。否则,beautifulsoup会引发异常。我是否应该为Pojo创建messagebodywriter并实现它以编写空元素?CXF应该能够立即序列化为XML。谢谢!我在客户端使用beautifulsoup解析xml,并希望其中包含空元素。否则,beautifulsoup会引发异常。我是否应该为Pojo创建messagebodywriter并实现它以编写空元素?CXF应该能够立即序列化为XML。