我正在尝试使用 JAXB 生成类似这样的内容:
<person>
<firstName>Foo</firstName>
<lastName>Bar</lastName>
<identities>
<green id="greenId">
<some_elements....
</green>
<blue id="blueId"/>
</identities>
<identities>
的子元素都源于一个共同的父类(super class)。
在 Java 中是这样的:
@XmlRootElement(name = "person")
public class Person {
public String firstName;
public String lastName;
@XmlElementWrapper(name = "identities")
public Set<Identity> identities = new HashSet<Identity>();
}
在哪里Identity
是 Blue
的父类(super class), Green
和其他一些人。
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 {}
如何正确注释类以获得我需要的内容?目前,输出是这样的:
<identities>
<identities id="0815"/>
</identities>
最佳答案
只需修改您的示例以在 identities 属性上使用 @XmlElementRef 注释。
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>();
}
关于java - 使用 JAXB 映射包含父类(super class)型和子类型的 Java 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4047998/