Hey,
I have 2 classes.
When I’m trying to create an XML structure from them, I only get the root element (A).
Why? Am I using wrong annotations?
@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A{
@XmlElement
int a;
protected A(){
}
}
@XmlAccessorType(XmlAccessType.FIELD)
public class B extends A{
@XmlElement
int b;
protected B(){
}
}
You probably need to use
@XmlSeeAlsoannotation in your top class:I wrote ‘probably’, because it depends on how do you set up your JAXB context. Basically you need to make sure all the classes which are supposed to be serialized are known to JAXB. If your
Bclass is not mentioned anywhere else (e.g. as a property type of one of classes whichare already known to JAXB), then JAXB has no chance to know how to serialize instances of
B. The intention of@XmlSeeAlsoannotation is to make sure JAXB looks into these listed classes too.UPDATE:
Alternatively you can provide the list of all the subclasses when creating the
JAXBContextobject usingJAXBContext.newInstance(Class...), e.g.:instead of
which you probably already do.
But my opinion this is a worse solution, because it makes you think of related classes every time you use JAXB in your code. In the top solution you set the relations once forever.