2017-06-05 92 views
0

在我當前的程序中,我目前嘗試使用JAXB將java中的數據結構編組爲xml文件。哈希映射數組必須被編組。這不起作用:儘管xml包含x個hashmap標記,但它們都是空的,無論它們內部是什麼內容。例如看看下面的類:JAXB Marshall散列圖陣列

類阿特拉斯:

@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而不是它們的數組),則HashMap的輸出是正確的。我也試圖介紹包裝,但它也不起作用。

所以你能給我一個提示我該怎麼做?是否需要自定義適配器? (如果是的話,爲什麼?)

在此先感謝!

+0

'new HashMap [] { map1,map2 });'你可以這樣做嗎? – SomeDude

+0

哎呀,你說得對,應該是非通用數組創建 – Myridos

+0

請在問題中提供正確的信息。 – SomeDude

回答