Xstream 在解组时不维护子元素的顺序 [英] Xstream does not maintain order of child elements while unmarshalling
问题描述
如何维护 Set 中未编组的子对象的顺序.下面是我的 xml,当转换为 java 对象时,我在集合中获得的顺序不是 A、B、C.我怎样才能做到这一点?
<emp name="A"/><emp name="B"/><emp name="C"/></公司>
观察:
在我的 Company.class 中,我定义了
Set
并且当 xstream 对其进行解组时,它会将集合创建为 HashMap,因此不维护顺序.问题) 如何在xstream中使用LinkedHashMap来维护订单?然后我将员工集定义为
LinkedHashSet
.将此 xstream 创建集设置为 LinkedHashMap 并保持顺序,但 Hibernate 抛出异常,因为我已经定义了 Set<set name="employees">
并且它在将 Set 转换为 LinkedHashSet 时引发错误
<块引用>
public void setEmployees(Set emps){this.packages = (LinkedHashSet)emps;}
我使用我的自定义转换器解决了这个问题,但我想必须有更好的方法来使用自定义转换器来解决这样一个小问题.我会继续寻找,但在那之前.
添加这个
xstream.registerConverter(new CompanyConverter());公共对象解组(HierarchicalStreamReader 阅读器,UnmarshallingContext 上下文){公司补偿 = 新公司();设置<员工>包 = new LinkedHashSet();而(读者.hasMoreChildren()){reader.moveDown();if("emp".equals(reader.getNodeName())){雇员 emp = (雇员)context.convertAnother(comp, Employee.class);员工添加(emp);}reader.moveUp();}comp.setEmployees(员工);回报补偿;}
How maintain the order of unmarshalled child objects in a Set. Below is my xml, when converting to java objects order that I get in set is not A,B,C. How can I achieve that?
<company id="abc">
<emp name="A"/>
<emp name="B"/>
<emp name="C"/>
</company>
Edit: Observations:
In my Company.class I had defined
Set<Employee>
and when xstream unmarshall it, it create the set as HashMap, so the order is not maintained. Ques) How can I use LinkedHashMap in xstream to maintain the order?Then I defined the employee set as
LinkedHashSet<Employee>
. Doing this xstream create set as LinkedHashMap and order is maintained but Hibernate throws exception because there I have defined Set<set name="employees">
and it throws error on casting Set to LinkedHashSet
public void setEmployees(Set<Employee> emps){ this.packages = (LinkedHashSet<Employee>)emps; }
I solved the problem using my custom Converter but I guess there has to be a better way that to used custom converter for such a small problem. I'll keep looking but until then.
Add this
xstream.registerConverter(new CompanyConverter());
public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {
Company comp = new Company();
Set<Employee> packages = new LinkedHashSet<Employee>();
while(reader.hasMoreChildren()){
reader.moveDown();
if("emp".equals(reader.getNodeName())){
Employee emp = (Employee)context.convertAnother(comp, Employee.class);
employees.add(emp);
}
reader.moveUp();
}
comp.setEmployees(employees);
return comp;
}
这篇关于Xstream 在解组时不维护子元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!