我正在尝试使用JAXB来序列化XML中的类。
@XmlRootElement
class Foo
{
Hashtable<String, Hashtable<String, Integer>> table = new Hashtable<>();
public Hashtable<String, Hashtable<String, Integer>> getTable() {
return table;
}
public void setTable(Hashtable<String, Hashtable<String, Integer>> t) {
table = t;
}
}
但是,这会产生带有空值的XML(我向您保证这些值实际上是存在的!)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Foo>
<table>
<entry>
<key>Test key</key>
<value/>
</entry>
</table>
</Foo>
有简单的方法可以解决此问题吗?除非确实需要,否则我真的不想使用
@XmlJavaTypeAdapters
。使用普通哈希表可以正常工作:
Hashtable<String, Integer>> table = new Hashtable<>();
最佳答案
抱歉让您失望,但目前尚无简单的方法来修复它。外部哈希表和内部哈希表之间存在显着差异。外层是一个属性,由com.sun.xml.bind.v2.runtime.property.SingleMapNodeProperty<BeanT, ValueT>
类在内部处理。此类为将映射表示为键/值条目做了一些魔术。
但是,对于内部哈希表,它不是“静态”属性,而是动态属性。这就是为什么它由通用com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl
处理的原因。此类在Hashtable中找不到任何JAXB属性(即java bean属性-同时具有getter和setter)。结果,您得到空的value
元素。
由于相同的原因,以下动态Hashtable属性也不起作用:
@XmlRootElement
@XmlSeeAlso(Hashtable.class)
public static class TypeWithHashtableAsObject {
private Object property;
public Object getProperty() {
return property;
}
public void setProperty(Object property) {
this.property = property;
}
}
...
TypeWithHashtableAsObject foo = new TypeWithHashtableAsObject();
Hashtable<String, Integer> property = new Hashtable<>();
property.put("innerKey", 12);
foo.setProperty(property);
StringWriter writer = new StringWriter();
marshaller.marshal(foo, writer);
System.out.println(writer.toString());
结果:
<typeWithHashtableAsObject>
<property xsi:type="hashtable" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</typeWithHashtableAsObject>
那是空元素。
In another answer您可以找到更多如何封送嵌套集合的示例。另一个解决方案是用其他类型包装Hashtable。像表:
public class Table {
private Hashtable<String, Integer> table = new Hashtable<>();
public Table(Hashtable<String, Integer> table) {
this.table = table;
}
public Table() {
}
public Hashtable<String, Integer> getTable() {
return table;
}
public void setTable(Hashtable<String, Integer> table) {
this.table = table;
}
}
并将
Foo.table
类型更改为Hashtable<String, Table>
。结果比原始结果更冗长,但恕我直言非常一致:
<foo>
<table>
<entry>
<key>key1</key>
<value>
<table>
<entry>
<key>innerKey</key>
<value>12</value>
</entry>
</table>
</value>
</entry>
</table>
</foo>