W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
改造需要的代碼量比較多,因為JAXB原生不指定Map的自定義操作。也可以說JAXB不支持Map這種數(shù)據(jù)類型。所以需要使用到適配器來擴展Jaxb的功能。
首先定義一個類,其中只有兩個字段,為了簡單,可以不寫setters/getters方法。通過這種方式模擬一個Map,只包含key/value,也就是first/second,這個名稱就是XML的節(jié)點顯示名稱。
public class XmlMap {
public String first;
public String second;
}
自定義一個Adapter
,這里將所有的代碼都展示出來。
public class MapAdapter extends XmlAdapter<XmlMap[], Map<String, String>>{
@Override
public Map<String, String> unmarshal(XmlMap[] v) throws Exception {
Map<String, String> map = new HashMap<>();
for(int i=0;i<v.length;i++) {
XmlMap pairs = v[i];
map.put(pairs.first, pairs.second);
}
return map;
}
@Override
public XmlMap[] marshal(Map<String, String> v) throws Exception {
XmlMap[] xmlMap = new XmlMap[v.size()];
int index = 0;
for(Map.Entry<String, String> entry: v.entrySet()) {
XmlMap xm = new XmlMap();
xm.first = entry.getKey();
xm.second = entry.getValue();
xmlMap[index++] = xm;
}
return xmlMap;
}
}
@XmlJavaTypeAdapter
JAXB能夠內(nèi)置支持List和Set集合,但是對于Map的支持需要自己處理。它繼承自抽象類XmlAdapter<ValueType,BoundType>
類型參數(shù):
這里的Map對于JAXB是一個未知類型,但是XmlMap[]
卻是已知的對象數(shù)組類型。通過中間的轉(zhuǎn)化賦值,可以使XmlMap[]
與Map
相互轉(zhuǎn)化,從而讓Jaxb知道數(shù)據(jù)如何處理。
在之前的Product中,在Map上加上注解@XmlJavaTypeAdapter(MapAdapter.class)
。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Product2 {
private String id;
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> category;
// setters, getters
測試一下:
@Test
public void test2() throws JAXBException {
Map<String, String> map = new HashMap<>();
map.put("衣服", "大衣");
map.put("褲子", "西褲");
Product2 product = new Product2();
product.setId("1402");
product.setCategory(map);
JAXB.marshal(product, System.out);
}
得到的結(jié)果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product2>
<id>1402</id>
<category>
<item>
<first>衣服</first>
<second>大衣</second>
</item>
<item>
<first>褲子</first>
<second>西褲</second>
</item>
</category>
</product2>
上面的所有節(jié)點名稱除了item
都是可以通過一定的方法改變的。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: