)
I have an xmlelement which can be from different Types. Independent of the type it has the same name. It can be an object or just a reference via URI to an existing object. I thought xmlElements could be the solution. Marshalling works fine but by unmarshalling it, it chooses everytime the last given class type.
The Class Flower which contains the Element
@XmlRootElement(name = "Flower")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "id", "name", "refName", "description", "created", "updated", "color",
"seed")
public class Flower extends CommonElements{
private string color;
@XmlElements({
@XmlElement(name="seed", type=Seed.class),
@XmlElement(name="seed", type=Reference.class)
})
public Object seed;
}
The class seed which is one of the Types the element can contain
@XmlRootElement(name = "Seed")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "id", "name", "refName", "description", "created", "updated",
"category", "country"})
public class Seed extends CommonElements{
protected String category = "";
protected String country = "";
}
And the other class which can be contained by the element
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Reference {
@XmlAttribute(name="href")
protected URI href;
}
In CommonElements are just some generic elements like id, refName, description etc.. The XML can look like
<Flower>
<id>http://localhost/test/flowers/1</id>
<refName>redRose</refName>
<description>classical red rose </description>
<color>red</color>
<seed href="http://localhost/test/seeds/1" />
</Flower>
Or like
<Flower>
<id>http://localhost/test/flowers/1</id>
<refName>redRose</refName>
<description>classical red rose </description>
<color>red</color>
<seed>
<id>http://localhost/test/seeds/1</id>
<refName>wildrose</refName>
<description>Special Seed for beautiful wild roses</description>
<category>wildrose</category>
<country>china</country>
</seed>
</Flower>
I assumed that the different structure of the classes are enough for jaxb to distinguish the objects. I am afraid I have to use adapters but I hope someone has another great idea.
I know there is one Topic similiar to mine. But the types in the topic looks alike so jaxb can't distinguish them. (JAXB @XmlElements, different types but same name?)
Thanks and sorry for my bad english.
Edit: Is there a way to add the type by marshalling, that jaxb knows exactly which type it is for unmarshalling?