![](/img/trans.png)
[英]JAXB: how to marshall HashMap<String, HashMap<String, String>>?
[英]How to Marshall HashMap<String, ArrayList<String>> using JAXB
我正在嘗試編組 HashMap>,但 ArrayList 在生成 xml 時為空。
我嘗試了以下代碼。
POJO -
@XmlRootElement(name = "crossreference")
@XmlAccessorType(XmlAccessType.FIELD)
public class CrossReference implements Serializable {
private static final long serialVersionUID = 1L;
HashMap<String, ArrayList<String>> testMap = new HashMap<>();
public HashMap<String, ArrayList<String>> getTestMap() {
return testMap;
}
public void setTestMap(HashMap<String, ArrayList<String>> testMap) {
this.testMap = testMap;
}
@Override
public String toString() {
return "CrossReference [testMap=" + testMap + "]";
}
馬歇爾的代碼,
ArrayList<String> nameList = new ArrayList<>();
nameList.add("Shivling");
nameList.add("Bipin");
nameList.add("Sudhakar");
HashMap<String, ArrayList<String>> testMap = new HashMap<>();
testMap.put("name", nameList);
CrossReference crossReference = new CrossReference();
crossReference.setTestMap(testMap);
JAXBContext context = JAXBContext.newInstance(CrossReference.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
StringWriter stringWriter = new StringWriter();
marshaller.marshal(crossReference, stringWriter);
String xml = stringWriter.toString();
System.out.println(xml);
編組后的 XML -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<crossreference>
<testMap>
<entry>
<key>name</key>
<value/>
</entry>
</testMap>
</crossreference>
我不確定為什么 XML 上面的值是空的。 請幫我解決這個問題。
我期待 XML 的所有名稱如下,
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<crossreference>
<testMap>
<entry>
<key>name</key>
<value>Shivling</value>
<value>Bipin</value>
<value>Sudhakar</value>
</entry>
</testMap>
</crossreference>
首先,由於Map
只有一個value
,因此使用這種結構是不可能得到這樣的結果的。 盡管該value
是項目列表,但對於 map,它仍然是一個值。
JAXB 無法處理復雜/嵌套的數據結構,例如Map<String, List<String>>
。 你必須創建一個包裝前。 WrappedStringList
的值的 WrappedStringList,即Map<String, WrappedStringList>
。
class WrappedStringList {
private List<String> wrapped;
// getter & setter
}
它將用於 object CrossReference
參考,例如:
@XmlElementWrapper(name = "testMap")
HashMap<String, WrappedStringList> testMap = new HashMap<>();
結果如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<crossreference>
<testMap>
<entry>
<key>name</key>
<value>
<wrapped>Shivling</wrapped>
<wrapped>Bipin</wrapped>
<wrapped>Sudhakar</wrapped>
</value>
</entry>
</testMap>
</crossreference>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.