I am trying to unmarshal a 3rd party XML payload into a class. The problem is that the payload has a parent/child relationship and the root node, the parent and the children all have the same element name. Here is a sample of the payload.
<?xml version="1.0" encoding="UTF-8"?>
<Directory>
<id>2</id>
<name>Media</name>
<Directory>
<id>5</id>
<name>Default_Content</name>
<Directory>
<id>9</id>
<name>Images</name>
</Directory>
<Directory>
<id>8</id>
<name>Icons</name>
</Directory>
<Directory>
<id>6</id>
<name>Additional_Content</name>
</Directory>
</Directory>
<Directory>
<id>12</id>
<name>IC</name>
</Directory>
</Directory>
So I am trying to annotate a class so JAXB/JAX-RS can unmarshal this into something useful.
I’ve tried something like this
@XmlRootElement(name="Directory")
public class Directory {
private int id;
private String name;
@XmlElement(name="Directory");
private List<Directory> directories = new ArrayList<Directory>();
}
But, predictably, it throws an IllegalAnnotationException because of having 2 properties with the same name.
Any ideas as to how I can use JAXB/JAX-RS to cleanly handle this mess or should I just parse it on my own?
Short Answer
The exception is due to a field/property collision. You can either annotate the properties (get methods) or set the following annotation on your type:
Long Answer
JAXB’s default access type is
PUBLIC_MEMBERthis means that JAXB will map all public fields (instance variables) and properties (get/set methods).If you annotate a field:
Then JAXB will think it has two
barproperties mapped and thrown an exception:The solution is to annotate the property and set the XmlAccessType type to
FIELDYour Model
Directory
Demo