私の現在のプログラムでは、JAXBを使用してjavaでデータ構造をXMLファイルにマーシャリングしようとしています。ハッシュマップの配列をマーシャリングする必要があります。これは完了しません。xmlにはx個のhashmapタグが含まれていますが、内容に関係なくすべてが空です。JAXB Harshmapのマーシャル配列
クラスアトラス:
@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の配列を削除した場合(配列の代わりに単一のハッシュマップのみをマーシャルする)、ハッシュマップの出力は正しいです。私もWrapperを導入しようとしましたが、どちらも動作しません。
私は何をしなければならないと思いますか?カスタムアダプターは必要ですか? (もしそうなら、理由は?)
ありがとうございました!
「新しいHashMap [] { map1、map2 });これは可能ですか? –
SomeDude
whoops、そうです、非ジェネリックアレイ作成でした。 – Myridos
質問に正しい情報を入力してください。 – SomeDude