在 JAXB 中解组 TreeSet
我有一个类,希望使用 JAXB 使用 XML 文件中的内容填充该类。我的 XML 文件看起来与此类似:
<root>
<mylist>
<item id="1">First Item</item>
<item id="2">Second Item</item>
</mylist>
</root>
我的 JAXB 带注释的类看起来像:
@XmlRootElement
class MyParentClass {
// I always populate this with a TreeSet
private Set<MyFieldItem> items;
public void setItems(Set<MyFieldItem> items) {
this.items = items;
}
@XmlElementWrapper("mylist") @XmlElement("item")
public Set<MyFieldItem> getItems() {
return items;
}
}
class MyFieldItem implements Comparable<MyFieldItem> {
private Integer id;
private String value;
public void setId(Integer id) {
this.id = id;
}
@XmlAttribute
public Integer getId() {
return id;
}
public void setValue(String value) {
this.value = value;
}
@XmlValue
public String getValue() {
return value;
}
public int compareTo(MyfieldItem o) {
return this.id.compareTo(o.getId());
}
}
我发现这种安排可以正确地将我的对象序列化为 XML,但是当我尝试将其转换回时,我使用的 TreeSet 变成了 >哈希集。
理论上,我的集合可以修复为 TreeSet (这确实解决了问题),但我宁愿正确配置 JAXB 并将该逻辑推迟到其他地方。我如何告诉 JAXB 构建 TreeSet?
I have a class that I wish to populate with content from an XML file using JAXB. My XML file looks similar to this:
<root>
<mylist>
<item id="1">First Item</item>
<item id="2">Second Item</item>
</mylist>
</root>
My JAXB annotated classes look like:
@XmlRootElement
class MyParentClass {
// I always populate this with a TreeSet
private Set<MyFieldItem> items;
public void setItems(Set<MyFieldItem> items) {
this.items = items;
}
@XmlElementWrapper("mylist") @XmlElement("item")
public Set<MyFieldItem> getItems() {
return items;
}
}
class MyFieldItem implements Comparable<MyFieldItem> {
private Integer id;
private String value;
public void setId(Integer id) {
this.id = id;
}
@XmlAttribute
public Integer getId() {
return id;
}
public void setValue(String value) {
this.value = value;
}
@XmlValue
public String getValue() {
return value;
}
public int compareTo(MyfieldItem o) {
return this.id.compareTo(o.getId());
}
}
I find that this arrangement serialises my objects to XML correctly, but when I try to convert it back the TreeSet I use becomes a HashSet.
In theory my collection could be fixed to a TreeSet (which does fix the problem), but I'd rather configure JAXB correctly and defer that logic elsewhere. How do I tell JAXB to build a TreeSet instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决此问题的最简单方法是将您的
Set
属性预先初始化为适当的实现类型,以及您的 JAXB 实现(Metro、EclipseLink MOXy、Apache JaxMe 等)将使用它而不是创建新集:了解更多信息
The easiest way to solve this problem is pre-initialize your
Set
property to the appropriate implementation type, and your JAXB implmentation (Metro, EclipseLink MOXy, Apache JaxMe, etc) will use that instead of creating a new Set:For More Information