使用空字段的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文件中,我的输出中没有该元素。我想要做的是包括输出中的所有字段;如果它们为null,则将它们替换为 - 例如空白。所以输出应该是:
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>
谢谢,
Jalpesh。
推荐答案
谢谢你的回答。
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.
在泽西论坛的某个人向我指出文档后,我偶然发现了答案部分 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屋!