I'm switching from Castor to JAXB2 to perform marshaling/unmarshaling between XML and Java object. I'm having problem trying to configure a collection of polymorphic objects.
Sample XML
<project name="test project">
<orange name="fruit orange" orangeKey="100" />
<apple name="fruit apple" appleKey="200" />
<orange name="fruit orange again" orangeKey="500" />
</project>
Project class
The oranges
list works fine, I'm seeing 2 oranges in the list. But, I'm not sure how to configure fruitList
. The fruitList
should have 3 fruit: 2 oranges and 1 apple.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Project {
@XmlAttribute
private String name;
@XmlElement(name = "orange")
private List<Orange> oranges = new ArrayList<Orange>();
// Not sure how to configure this... help!
private List<Fruit> fruitList = new ArrayList<Fruit>();
}
Fruit class
Fruit is an abstract class. For some reason, defining this class as an abstract seems to be causing a lot of problems.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class Fruit {
@XmlAttribute
private String name;
}
Orange class
public class Orange extends Fruit {
@XmlAttribute
private String orangeKey;
}
Apple class
public class Apple extends Fruit {
@XmlAttribute
private String appleKey;
}
How do I configure my fruitList
in Project
to achieve what I want here?
Thanks much!
fruitList
property with@XmlElementRef
and annotatedOrange
andApple
classes with@XmlRootElement
. I ran the code, and thefruitList
came out empty. What am I doing wrong here? Thanks. – Medicament