我在 XSD 模式中有一个特定元素,我希望 JAXB 将空元素内容视为 null 而不是空字符串。模型类由XJC生成。
我见过this answer for marshalling empty string to null globally ,而且我一直使用 JAXB 的 RI,所以我猜这对我不起作用。
鉴于我只需要一个特定元素,我是否可以采取另一种方法?
最佳答案
由于这仅适用于一个元素,因此下面是一种可以使其与任何 JAXB 实现一起使用的方法。
Java 模型
福
利用 @XmlAccessorType
注释将您的类设置为使用字段访问。然后将元素对应的字段初始化为""
。实现 get
/set
方法,将 ""
视为 null
。
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
private String bar = "";
public String getBar() {
if(bar.length() == 0) {
return null;
} else {
return bar;
}
}
public void setBar(String bar) {
if(null == bar) {
this.bar = "";
} else {
this.bar = bar;
}
}
}
演示代码
下面是一些演示代码,您可以运行它来查看一切是否正常。
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar/>
</foo>
演示
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum18611294/input.xml");
Foo foo = (Foo) unmarshaller.unmarshal(xml);
System.out.println(foo.getBar());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
输出
null
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
<bar></bar>
</foo>
关于java - 强制 JAXB 将空元素解释为 Null 而不是空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18611294/