I have a list of objects with a common base class that I am trying to serialise as XML using jaxb. I would like the annotations of the derived classes to be used when marshalling, but I'm having trouble getting there.
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);
}
}
I would like:
<base_list>
<derived>
<baseValue>0</baseValue>
<derivedValue>1</derivedValue>
</derived>
<derived2>
<baseValue>0</baseValue>
<derivedValue>1</derivedValue>
</derived2>
</base_list>
However, the code above is giving:
<base_list>
<baseList>
<baseValue>0</baseValue>
</baseList>
<baseList>
<baseValue>0</baseValue>
</baseList>
</base_list>
Is there any way to force it to use the derived class? In the real situation I don't know ahead of time the classes that may derive from Base.
Note that I only need to marshal, not unmarshal the data.
You can use the @XmlElementRef
annotation to handle this use case. @XmlElementRef
corresponds to the concept of substitution groups in XML schema.
For an Example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With