注意:我是 EclipseLink JAXB (MOXy) 负责人,也是 JAXB 2.X (JSR-222) 专家组的成员。
使用 MOXy,您可以按照 Hovercraft Full Of Eels 的建议执行 XmlAdapter 方法。它看起来像:
布尔适配器
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class BooleanAdapter extends XmlAdapter<Boolean, Boolean> {
@Override
public Boolean unmarshal(Boolean v) throws Exception {
return Boolean.TRUE.equals(v);
}
@Override
public Boolean marshal(Boolean v) throws Exception {
if(v) {
return v;
}
return null;
}
}
事物
您使用@XmlJavaTypeAdapter 注释将您的属性与XmlAdapter 相关联,如下所示:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name="thing")
public class Thing{
private String name;
private boolean awesome;
@XmlValue public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@XmlAttribute
@XmlJavaTypeAdapter(BooleanAdapter.class)
public void setAwesome(boolean awesome) {
this.awesome = awesome;
}
public boolean isAwesome() {
return this.awesome;
}
}
演示
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Thing.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Thing thing = new Thing();
thing.setName("popcorn ball");
thing.setAwesome(false);
marshaller.marshal(thing, System.out);
thing.setAwesome(true);
marshaller.marshal(thing, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8"?>
<thing>popcorn ball</thing>
<?xml version="1.0" encoding="UTF-8"?>
<thing awesome="true">popcorn ball</thing>
使用 JAXB RI
如果您使用 JAXB RI 运行此示例,您将收到以下异常:
Exception in thread "main" com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Adapter example.BooleanAdapter is not applicable to the field type boolean.
this problem is related to the following location:
at @javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(type=class javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter$DEFAULT, value=class example.BooleanAdapter)
at public boolean example.Thing.isAwesome()
at forum251.Thing
更多信息