JAXB编组布尔成一个复杂的类型 [英] JAXB marshalling boolean into a complex type
问题描述
我在JAXB新的,我想做些什么,我不知道它是可行的。我有一个Java类马歇尔是这样的:
I am new in JAXB and I would like to do something i don't know if it's doable. I have a java class to marshall like this :
@XmlAccessorType(XMLAccessType.NONE)
public class MyClass {
@XmlElement
private String a = "x";
@XmlElement
private String b = "xx";
@XmlElement
private boolean c = true;
...
}
和希望像这样的XML输出:
and want XML output like this :
<?xml ...?>
<MyClass>
<a>x</a>
<b>xx</b>
<c value="true"/>
</MyClass>
一个解决方案我心目中是使用一个布尔包装类,使其工作,但我想避免这种情况,因为它需要我走能够使用布尔原始的真,假。
One solution i have in mind is to use a boolean wrapper class to make it work, but i would like to avoid this as it takes me away the ability to use boolean primitive true, false.
我们能做到在JAXB?
Can we do that in JAXB?
推荐答案
您可以创建一个 XmlAdapter
来得到你所寻找的行为。一个 XmlAdapter
转换域对象为另一种类型的编组和解组的目的。
Leverage An XmlAdapter
You could create an XmlAdapter
to get the behaviour you are looking for. An XmlAdapter
converts a domain object into another type for the purposes of marshalling and unmarshalling.
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class BooleanAdapter extends XmlAdapter<BooleanAdapter.AdaptedBoolean, Boolean> {
public static class AdaptedBoolean {
@XmlAttribute
public boolean value;
}
@Override
public Boolean unmarshal(AdaptedBoolean adaptedBoolean) throws Exception {
return adaptedBoolean.value;
}
@Override
public AdaptedBoolean marshal(Boolean v) throws Exception {
AdaptedBoolean adaptedBoolean = new AdaptedBoolean();
adaptedBoolean.value = v;
return adaptedBoolean;
}
}
使用 XmlAdapter
要使用 XmlAdapter
映射的领域将需要类型的布尔
而不是布尔
。您存取方法仍然可以布尔
如果你想。
To Use the XmlAdapter
To use the XmlAdapter
your mapped field will need to be of type Boolean
instead of boolean
. You accessor methods can still be boolean
if you want.
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.NONE)
public class MyClass {
@XmlElement
private String a = "x";
@XmlElement
private String b = "xx";
@XmlElement
@XmlJavaTypeAdapter(BooleanAdapter.class)
private Boolean c = true;
public boolean getC() {
return c;
}
public void setC(boolean c) {
this.c = c;
}
}
这篇关于JAXB编组布尔成一个复杂的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!