Mapping Java collections which contains super- and sub-types with JAXB

我怕爱的太早我们不能终老 提交于 2019-12-30 10:59:12

问题


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(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>

回答1:


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>();
}


来源:https://stackoverflow.com/questions/4047998/mapping-java-collections-which-contains-super-and-sub-types-with-jaxb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!