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;
}