gpt4 book ai didi

java - JAXB 忽略 HashMap 属性?

转载 作者:行者123 更新时间:2023-11-30 11:52:45 26 4
gpt4 key购买 nike

我正在使用 J2SE 附带的 JAXB 实现来序列化包含 HashMap 属性的 bean。我认为这应该开箱即用,因为 this

JAXB spec defines a special handling for Map when it's used as a propety of a bean. For example, the following bean would produce XMLs like the following: ...

这或多或少是有效的,除非结构有不止一层,即 HashMap 是 bean 的一个属性,它是 bean 的一个属性——像这样:

import java.util.HashMap;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.JAXB;

class bean {
@XmlElement public HashMap<String,String> map;
}

@XmlRootElement class b2 {
@XmlElement public bean b;
}


class foo {
public static void main(String args[]) {
try {
bean b = new bean();
b.map = new HashMap<String,String>();
b.map.put("a","b");
b2 two = new b2();
two.b=b;
JAXB.marshal(two, System.out);

} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}

这输出 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><b2><b><map/></b></b2>而不是正确格式化的 HashMap。如果我注释 bean 它会起作用与 @XmlRootElement并删除 @XmlElement来自 map ,但我不明白为什么这是必要的。应该是这样吗?

最佳答案

在您链接的网站上给出了解释:

Unfortunately, as of 2.1, this processing is only defined for bean properties and not when you marshal HashMap as a top-level object (such as a value in JAXBElement.) In such case, HashMap will be treated as a Java bean, and when you look at HashMap as a bean it defines no getter/setter property pair, so the following code would produce the following XML:

Bean with Map:

m = new HashMap();
m.put("abc",1);
marshaller.marshal(new JAXBElement(new QName("root"),HashMap.class,m),System.out);

XML representation:

<root />

This issue has been recorded as #223 and the fix needs to happen in later versions of the JAXB spec.

关于java - JAXB 忽略 HashMap 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6693155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com