键值对的 JaxB 编组,其中 Value 可以是另一个键、值对

JaxB Marshalling of a Key, Value Pair, where Value can be another Key, Value pair

提问人:dtchmnt 提问时间:10/23/2023 更新时间:10/23/2023 访问量:39

问:

我有这个对象,作为一个复杂对象的节点:

public class 参数实现 Serializable {

@XmlElement(name = "Key")
protected String key;
@XmlElement(name = "Value")
protected Object value;

}

属性“Value”可以是 String,有效地使 Parameter 成为 Map<String, String>,也可以是另一个 Parameter Value。 我有一个这些对象的列表。

例如,以下两个 XML 代码段都有效:

<Parameter>
<Key>MyKey</Key>
<Value>MyValue</MyValue>
</Parameter>

<Parameter>
<Key>Key1</Key>
<Value>
    <Key>Key2</Key>
    <Value>
        <Key>Key3</Key>
        <Value>ValueInString1</Value>
    </Value>
    <Value>
        <Key>Key4</Key>
        <Value>ValueInString2</Value>
    </Value>
</Value>

我正在寻找一种实现可以处理此问题的 XMLAdapter 的方法。 两个主要思想是:

  1. 将适配器用于整个参数类。
  2. 仅将适配器用于“值”属性。

想法 #1 卡在如何封送键值对列表上 想法 #2 卡住了,如果值是参数,如何调用参数的泛型编组器.class

java xsd maven-jaxb2-插件

评论


答:

0赞 Joel Victor 10/23/2023 #1

可以使用 MapAdapter 将 Map 转换为 MapElements 数组,如下所示:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;

    private MapElements() {
    } //Required by JAXB

    public MapElements(String key, String value) {
        this.key = key;
        this.value = value;
    }
}
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    public MapAdapter() {
    }

    public MapElements[] marshal(Map<String, String> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, String> r = new TreeMap<String, String>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}
0赞 dtchmnt 10/23/2023 #2

仅供参考:

  • JaxB 编组无法做到这一点。
  • 杰克逊可以做到这一点

我最终删除了 JaxB 注释,以便 Jackson 可以解析和打印所需的响应