我正在尝试将一个对象编码为 XML,该对象扩展 HashMap<String, List<String>>
。然而,我不清楚为什么输出不包含在此对象中输入的数据。用于将此对象编码为 XML 的方法可以在问题末尾附近找到。
示例1(实际情况)
数据结构:
@XmlRootElement
class WhatIWant extends HashMap<String, List<String>> {
}
使用以下方式填充:
WhatIWant what = new WhatIWant();
what.put("theKey", Arrays.asList("value1", "value2"));
结果输出如下,输入的数据无处可寻。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<whatIWant/>
<小时/>
示例2(产生预期结果的情况)
类似的东西确实有效,并且是我期望的第一个示例的输出看起来类似的内容。
数据结构:
@XmlRootElement
class MyHashmap {
public HashMap<String, MyList> map = new HashMap<>();
}
class MyList {
public List<String> list = new ArrayList<String>();
}
填充使用:
MyHashmap requirement = new MyHashmap();
MyList t = new MyList();
t.list = Arrays.asList("value1", "value2");
requirement.map.put("theKey", t);
结果输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myHashmap>
<map>
<entry>
<key>theKey</key>
<value>
<list>value1</list>
<list>value2</list>
</value>
</entry>
</map>
</myHashmap>
<小时/>
对象到 XML 方法
我用来将对象转换为 XML 的方法:
public static String getObjectAsXML(Object obj) {
try {
// Create marshaller
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshall the object
StringWriter sw = new StringWriter();
marshaller.marshal(obj, sw);
return sw.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
问题
- 为什么
Example 1
不生成类似于Example 2
中的输出?为什么根本不生成任何东西? - 应该如何获取类似
Example 1
的结构的 XML 输出?或者说这是不可能的?
最佳答案
原因可能有以下几种: 要编码/解码的元素必须是公共(public)的,或者具有 XMLElement 注释。
在第一个示例中,根类没有公共(public)元素,而第二个则有。您可以尝试添加(到第一个示例)一个返回映射条目的公共(public) getter(并将适当的 @XmlAccessorType 添加到 WhatIWant 类)并查看它是否给出预期结果
关于java - 使用 JAXB 将 HashMap<String, List<String>> 转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53536151/