本文介绍了使用JAXB映射包含超类和子类的Java集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用JAXB产生这样的东西:
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>
< identities>
在Java中,它是这样的:
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>();
}
其中 Identity
Blue
, Green
和其他一些超类。
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>
推荐答案
只需修改您的示例,使用@XmlElementRef注释的身份属性。
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>();
}
这篇关于使用JAXB映射包含超类和子类的Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!