繁体   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