簡體   English   中英

JAXB Hashmap的Marshall數組

[英]JAXB Marshall Array of Hashmap

在當前程序中,我目前嘗試使用JAXB將Java中的數據結構編組為xml文件。 哈希圖數組必須被整理。 這不能完全完成:盡管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的數組(僅封送一個哈希表而不是數組),則哈希表的輸出是正確的。 我也嘗試介紹了Wrapper,但它也不起作用。

那么,您能給我一個提示嗎? 是否需要自定義適配器? (如果是,為什么?)

提前致謝!

您需要一個自定義適配器,因為JAXB自然不會映射某些類,包括HashMap。

來源(用法部分的第一行): https : //docs.oracle.com/javase/7/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html

至於適配器的功能,則取決於所需的XML文件結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM