在我目前的程序中,我目前尝试使用JAXB将java中的数据结构编组到xml文件中。必须编组一个hashmap数组。这不起作用:虽然xml包含x hashmap标记,但它们都是空的,无论它们内部是哪个内容。例如,查看以下类:
班级地图集:
@XmlRootElement (name = "atlas")
@XmlAccessorType(XmlAccessType.FIELD)
public class Atlas {
@XmlElement(name = "file")
private String[] filePaths;
private int x, y;
@XmlElement(name = "objectDefinition")
private HashMap<Integer, Definition>[] objectDefinitions;
public void setObjectDefinitions(HashMap<Integer, Definition>[] defs) {
objectDefinitions = defs;
}
public void setFilePaths(String[] paths) {
filePaths = paths;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
班级定义:
@XmlAccessorType(XmlAccessType.FIELD)
public class Definition {
private int a, b;
public Definition(int a, int b) {
this.a = a;
this.b = b;
}
public Definition() {}
}
执行班级:
public class XmlLoader {
public static void execute() {
Atlas atlas = new Atlas();
atlas.setX(8);
atlas.setY(9);
atlas.setFilePaths(new String[] {
"path1", "path2"
});
Definition def1, def2, def3, def4;
def1 = new Definition(1,2);
def2 = new Definition(3,4);
def3 = new Definition(5,6);
def4 = new Definition(7,8);
HashMap<Integer, Definition> map1 = new HashMap<>();
map1.put(200, def1);
map1.put(202, def2);
HashMap<Integer, Definition> map2 = new HashMap<>();
map2.put(100, def3);
map2.put(101, def4);
atlas.setObjectDefinitions(new HashMap[] {
map1, map2
});
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Atlas.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(atlas, new File("out.xml"));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
这将产生以下输出:
<atlas>
<file>path1</file>
<file>path2</file>
<x>8</x>
<y>9</y>
<objectDefinition />
<objectDefinition />
</atlas>
这不是我所期望的。我会期待一些内容,但它不存在。如果我删除HashMap数组(只编组一个散列图而不是它们的数组),则hashmap的输出是正确的。我也试图介绍Wrapper,但它也不起作用。
那么你能给我一个提示我要做什么吗?是否需要自定义适配器? (如果是,为什么?)
提前致谢!
答案 0 :(得分:0)
您需要一个自定义适配器,因为JAXB不会自然地映射某些类,包括HashMap。
来源(使用部分的第一行):https://docs.oracle.com/javase/7/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html
关于适配器是什么,它取决于您希望的XML文件结构类型。