我有一个包含人类地图的世界。如果我整理课堂世界,我会得到以下输出:
<world>
<humans>
<human key="2">
<value>
<name>Tom</name>
</value>
</human>
<human key="1">
<value>
<name>Max</name>
</value>
</human>
</humans>
</world>
但我不想显示“价值”-Tag。它应该看起来像:
<world>
<humans>
<human key="2">
<name>Tom</name>
</human>
<human key="1">
<name>Max</name>
</human>
</humans>
</world>
这可能吗?
以下是世界和人类的代码:
@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);
}
}
答案 0 :(得分:2)
正如ilcavero所指出的,XmlAdapter
可用于在JAXB中将替代映射应用于Map(或任何类型)。以下是具体示例的链接:
了解更多信息
答案 1 :(得分:2)
我的解决方案
我将关键属性添加到人类,然后我将地图转换为数组:
@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 :(得分:1)
在您的情况下,它将应用于HumanEntry.value而不是XmlElement