In my current program I currently try to marshall a datastructure in java using JAXB into a xml file. An array of hashmap has to be marshalled. This does not work completley: While the xml contains x hashmap tags, they are all empty, no matter which content was inside them. For example look at the following classes:
Class Atlas:
@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;
}
}
Class Definition:
@XmlAccessorType(XmlAccessType.FIELD)
public class Definition {
private int a, b;
public Definition(int a, int b) {
this.a = a;
this.b = b;
}
public Definition() {}
}
Executing Class:
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();
}
}
}
This will produce the following output:
<atlas>
<file>path1</file>
<file>path2</file>
<x>8</x>
<y>9</y>
<objectDefinition />
<objectDefinition />
</atlas>
Which is not what I've expected. I would've expected some content inside the 's but it's not there. If I remove the Array of HashMap (only marshall a single hashmap instead of an array of them), the output of the hashmap is correct. I also tried to introduce Wrapper, but it does not work either.
So could you give me a hint what I've to do? Is a custom adapter needed? (And if yes, why?)
Thanks in advance!
You need a custom adapter, as JAXB does not naturally map some classes, including HashMap.
Source (First line of the usage part) : https://docs.oracle.com/javase/7/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html
As for what does the adapter, it depends on what kind of XML file structure you wish for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.