Wednesday, 8 January 2014

Using JAXB to Parse a List of Items and References

I recently hit a problem using JAXB to parse a list of items in XML that contains both the actual items and references to items.
  <item-ref uri="itemC.xml"/>
  <item-ref uri="itemD.xml"/>
I had implemented an adapter to transform an ItemRef instance to an Item, but the following code did not work as I had expected.
  @XmlElement(name = "item", type = Item.class),
  @XmlElement(name = "item-ref", type = ItemRef.class)
private List<ability> items = new LinkedList<item>();
Instead of applying the adapter to the item-ref elements, it applied the adapter to all elements mapped to the list (it took a while to work this one out). The fix was to create a new adapter class that mapped Item to Item and use this as the adapter for item-ref elements. If this adapter was passed an ItemRef, it adapted it to an Item, otherwise it returned it unmodified.