I'm trying to produce something like this with JAXB:
<person>
<firstName>Foo</firstName>
<lastName>Bar</lastName>
<identities>
<green id="greenId">
<some_elements....
</green>
<blue id="blueId"/>
</identities>
The child elements of <identities>
all stem from a common super-class.
In Java it's like this:
@XmlRootElement(name = "person")
public class Person {
public String firstName;
public String lastName;
@XmlElementWrapper(name = "identities")
public Set<Identity> identities = new HashSet<Identity>();
}
Where Identity
is a super class for Blue
, Green
and some others.
public class Identity {
@XmlID
@XmlAttribute
public String id;
}
@XmlRootElement开发者_JAVA百科(name = "blue")
public class Blue extends Identity {
public String oneOfManyFields;
}
@XmlRootElement(name = "green")
public class Green extends Identity {}
How do I properly annotate the classes to get what I need? Currently, the output is like so:
<identities>
<identities id="0815"/>
</identities>
Simply modify your example to use the @XmlElementRef annotation on the identities property.
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "person")
public class Person {
public String firstName;
public String lastName;
@XmlElementWrapper(name = "identities")
@XmlElementRef
public Set<Identity> identities = new HashSet<Identity>();
}
精彩评论