【问题标题】:JAXB marshalling a map without adapterJAXB 在没有适配器的情况下编组地图
【发布时间】:2023-03-29 23:52:01
【问题描述】:

我有一个 Map,我想将它编组为 XML。只要有大量不同类型的地图,我真的不想为每个地图编写自定义 XmlAdapter。 对于我用作键的所有类,我都有 XmlAdapters。当我独立编组这些类时,它们可以完美地工作,但是当我编组映射时,键会被忽略。我得到的只是以下 XML:

<entry>
    <key/>
    <value>
        <id>1</id>
        <property>something</property>
    </value>
</entry>

我想要的是:

<entry>
    <key>
        <property>something</property>
    </key>
    <value>
        <id>1</id>
        <property>something</property>
    </value>
</entry>

有没有一种方法可以在不为每个地图编写自定义 XmlAdapter 的情况下实现所需的结果?

【问题讨论】:

  • 谢谢。但我在编组 地图时没有问题。当我使用自定义类作为映射键时出现问题
  • 你没有什么特别的。我们会为那个用例做。您在尝试时遇到了什么问题?
  • 请添加您的自定义课程代码。

标签: java jaxb


【解决方案1】:

对于 JAXB 和 java.util.Map,您不需要做任何特别的事情。下面我用一个例子来演示。

Java 模型

Foo

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Foo {

    private Map<Bar, Bar> bars = new HashMap<Bar, Bar>();

    public Map<Bar, Bar> getBars() {
        return bars;
    }

    public void setBars(Map<Bar, Bar> bars) {
        this.bars = bars;
    }

}

条形

public class Bar {

    private String baz;

    public String getBaz() {
        return baz;
    }

    public void setBaz(String baz) {
        this.baz = baz;
    }

}

演示代码

演示

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Foo foo = new Foo();

        Bar bar1 = new Bar();
        bar1.setBaz("Hello");

        Bar bar2 = new Bar();
        bar2.setBaz("World");

        foo.getBars().put(bar1, bar2);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bars>
        <entry>
            <key>
                <baz>Hello</baz>
            </key>
            <value>
                <baz>World</baz>
            </value>
        </entry>
    </bars>
</foo>

更多信息

我在博客上写了更多关于 JAXB 和 java.util.Map 的文章:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多