JAXB - Unmarshalling polymorphic objects

I have been provided with XML that looks (of course, a lot of additional attributes):

<inventory>
  <item kind="GRILL" tag=123 brand="WEBER"/>
  <item kind="CAR" tag=124 make="FORD" model="EXPLORER" />
</inventory>

with about a dozen different species. I am using annotations to display java classes that look like this:

@XmlRootElement(name="inventory")
public class Inventory {
  @XmlElement(name="item")
  public List<Item> itemList = new LinkedList<Item>;
}
abstract public class Item {
  @XmlAttribute public int tag;
}
public class Grill extends Item {
  @XmlAttribute public string brand;
}
public class Car extends Item {
  @XmlAttribute public string make;
  @XmlAttribute public string model;
}

How can I get JAXB to create Item subclass objects based on the "kind" field?

+5
source share
1 answer

There are several different approaches in the field:

JAXB (JSR-222)

JAXB (Metro, MOXy, JaxMe ..). XmlAdapter, . XmlAdapter . . :

EclipseLink JAXB (MOXy)

@XmlDescriminatorNode EclipseLink JAXB (MOXy) .

:

EclipseLink 2.2:

+4

All Articles