我有一个带有公共基类的对象列表,我试图使用jaxb将其序列化为XML。我想在编组时使用派生类的注释,但是我遇到了麻烦。
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
public class Runner {
@XmlRootElement(name="base")
public static abstract class Base {
public int baseValue;
public Base() {
this.baseValue = 0;
}
}
@XmlRootElement(name="derived")
public static class Derived extends Base {
public int derivedValue;
public Derived() {
super();
this.derivedValue = 1;
}
}
@XmlRootElement(name="derived2")
public static class Derived2 extends Base {
public int derivedValue;
public Derived() {
super();
this.derivedValue = 1;
}
}
@XmlRootElement(name="base_list")
public static class BaseList {
public List<Base> baseList;
}
public static void main(String[] args) throws JAXBException {
BaseList baseList = new BaseList();
baseList.baseList = Arrays.asList((Base) new Derived(), (Base) new Derived());
JAXBContext jaxbContext = JAXBContext.newInstance(BaseList.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(baseList, System.out);
}
}
我想:
<base_list>
<derived>
<baseValue>0</baseValue>
<derivedValue>1</derivedValue>
</derived>
<derived2>
<baseValue>0</baseValue>
<derivedValue>1</derivedValue>
</derived2>
</base_list>
但是,上面的代码给出了:
<base_list>
<baseList>
<baseValue>0</baseValue>
</baseList>
<baseList>
<baseValue>0</baseValue>
</baseList>
</base_list>
有没有办法强迫它使用派生类?在实际情况中,我事先并不知道可能来自Base的类。
请注意,我只需要编组,而不是解组数据。
答案 0 :(得分:4)
您可以使用@XmlElementRef
注释来处理此用例。 @XmlElementRef
对应于XML模式中替换组的概念。
例如: