Jaxb map sorting issues

I have a cool world that contains a map of people. If I marshal the world of classes, I get the following output:

<world> <humans> <human key="2"> <value> <name>Tom</name> </value> </human> <human key="1"> <value> <name>Max</name> </value> </human> </humans> </world> 

But I do not want to display the "value" -Tag. It should look like this:

 <world> <humans> <human key="2"> <name>Tom</name> </human> <human key="1"> <name>Max</name> </human> </humans> </world> 

Is it possible?

Here is the code of the world of class and man:

 @XmlRootElement public class Human { @XmlElement private String name; public Human(){} } @XmlRootElement public class World { private Map<String, Human> humans = new HashMap<String, Human>(); public World(){} @XmlElementWrapper( name = "humans") @XmlElement(name = "human") public HumanEntry[] getMap() { List<HumanEntry> list = new ArrayList<HumanEntry>(); for (Entry<String, Human> entry : humans.entrySet()) { HumanEntry mapEntry =new HumanEntry(); mapEntry.key = entry.getKey(); mapEntry.value = entry.getValue(); list.add(mapEntry); } return list.toArray(new HumanEntry[list.size()]); } public void setMap(HumanEntry[] arr) { for(HumanEntry entry : arr) { this.humans.put(entry.key, entry.value); } } public static class HumanEntry { @XmlAttribute public String key; @XmlElement public Human value; } public void addHuman(String key, Human human){ this.humans.put(key, human); } } 
+2
source share
3 answers

As ilcavero noted, the XmlAdapter can be used to apply an alternate mapping to a Map (or any type) in JAXB. Below is a link to a specific example:

Additional Information

+2
source

My decision

I added a key attribute for the person, and then converted the map to an array:

 @XmlRootElement public class World { @XmlJavaTypeAdapter(HumanAdapter.class) private Map<String, Human> humans = new HashMap<String, Human>(); public World(){} } public class Human { @XmlElement private String name; @XmlAttribute(name="key") private String key; public Human(){} } public class HumanAdapter extends XmlAdapter<HumanJaxbCrutch, Map<String, Human>> { @Override public HumanJaxbCrutch marshal(Map<String, Human> humans) throws Exception { List<Human> list = new ArrayList<Human>(); for (Entry<String, Human> entry : humans.entrySet()) { list.add(entry.getValue()); } HumanJaxbCrutch humanJaxbCrutch = new HumanJaxbCrutch(); humanJaxbCrutch.setCourses(list.toArray(new Human[list.size()])); return humanJaxbCrutch; } @Override public Map<String, Human> unmarshal(HumanJaxbCrutch humans) throws Exception { Map<String, Human> map = new HashMap<String, Human>(); for(Human human : humans.getCourses()){ map.put(human.getKey(), human); } return map; } } class HumanJaxbCrutch { private Human[] courses; @XmlElement(name = "human") public Human[] getCourses() { return courses; } public void setCourses(Human[] courses) { this.courses = courses; } } 
+2
source
+1
source

All Articles