Problems marshalling a map in Jaxb

前端 未结 3 367
刺人心
刺人心 2021-01-15 15:33

I have a class world that contains a map of humans. If I marshal the class world I get following output:


    
        &l         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 16:07

    My solution

    I added the key attribute to human and then I converted the map to an array:

    @XmlRootElement
    public class World {
    
        @XmlJavaTypeAdapter(HumanAdapter.class)
        private Map humans = new HashMap();
    
        public World(){}
    }
    
    public class Human {
    
        @XmlElement
        private String name;
    
        @XmlAttribute(name="key")
        private String key;
    
        public Human(){}
    }
    
    public class HumanAdapter extends XmlAdapter> {
    
        @Override
        public HumanJaxbCrutch marshal(Map humans) throws Exception {
            List list = new ArrayList();
            for (Entry entry : humans.entrySet()) {
                list.add(entry.getValue());
            }
    
            HumanJaxbCrutch humanJaxbCrutch = new HumanJaxbCrutch();
            humanJaxbCrutch.setCourses(list.toArray(new Human[list.size()])); 
    
            return humanJaxbCrutch;
        }
    
        @Override
        public Map unmarshal(HumanJaxbCrutch humans) throws Exception {
            Map map = new HashMap();
    
            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;
        }
    }
    

提交回复
热议问题