带有空字段的 JAXB 编组 [英] JAXB Marshalling with null fields
问题描述
这是一个非常简单的请求,但我只是没有找到实现它的方法.
This is a pretty simple request, but I just didn't find a way to do it.
我基本上是在尝试在 JAXB 中设置一个角色,该角色表示每当遇到空字段时,不要在输出中忽略它,而是将其设置为空值.所以对于班级:
I'm basically trying to set up a role in JAXB which says that whenever an null field is encountered, instead of ignoring it in the output, set it to an empty value. So for the class :
@XMLRootElement
Class Foo {
Integer num;
Date date;
….
}
如果日期字段为空,则将其编组到 XML 文件中时,我的输出中不包含该元素.我想要做的是在输出中包含所有字段;如果它们为空,请将它们替换为 - 说一个空白.所以输出应该是:
When this has been marshalled into the XML file if the date field is null, my output does not have that element in it. What I want to do is include all the fields in the output; and if they are null, replace them with - say a blank. So the output should be :
<foo>
<num>123</num>
<date></date>
</foo>
谢谢,
贾尔佩什.
推荐答案
感谢大家的回答.
Chris Dail - 我尝试了你的方法,但它并没有真正达到我想要的效果.尽管为我的字段定义了默认值,但 JAXB 仍然忽略我的空值.
Chris Dail - I tried your approach, and it didn't really do what I wanted. JAXB was still ignoring my null values, in spite of defining a default value for my fields.
在 Jersey 论坛中有人将我指向文档部分后,我确实偶然发现了答案2.2.12.8 无值.
I did stumble across the answer after somebody in the Jersey forums pointed me to documentation section 2.2.12.8 No Value.
基本上,我所要做的就是将以下内容添加到我的字段中:
Basically, all I had to do was to add the following to my fields :
@XmlElement(nillable = true)
一旦我添加了这些字段,JAXB 就会在将它们编组到 XML 时显示这些字段,如下所示:
Once I added that, JAXB would show up those fields when marshalling them to XML like this:
...
<num>5</num>
<date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
....
这篇关于带有空字段的 JAXB 编组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!