使用 JAXB 映射包含超类型和子类型的 Java 集合
我正在尝试使用 JAXB 生成类似的内容:
<person>
<firstName>Foo</firstName>
<lastName>Bar</lastName>
<identities>
<green id="greenId">
<some_elements....
</green>
<blue id="blueId"/>
</identities>
的子元素都源于一个公共超类。
在 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
、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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需修改您的示例以在 identities 属性上使用 @XmlElementRef 注释即可。
Simply modify your example to use the @XmlElementRef annotation on the identities property.