我有一个我想要编组的对象。
@XmlRootElement
public class BoxItem {
@XmlElement
Map<Integer, ArrayList<String>> intgerStringArrMap;
BoxItem() {
intgerStringArrMap = new HashMap<Integer, ArrayList<String>>();
for (int i = 0; i < 3; i++) {
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int j = 0; j < 10; j++) {
stringArrayList.add(new BigInteger(130, new SecureRandom()).toString(32));
}
intgerStringArrMap.put(i, stringArrayList);
}
}
}
现在让我们假设我们有一个boxItem = new BoxItem()
如果我调用jaxbMarshaller.marshal(boxItem,System.out);,每个条目的值都为空。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<boxItem>
<intgerStringArrMap>
<entry>
<key>0</key>
<value/>
</entry>
<entry>
<key>1</key>
<value/>
</entry>
<entry>
<key>2</key>
<value/>
</entry>
</intgerStringArrMap>
</boxItem>
如何在Map值中对ArrayList中的元素进行编组?
答案 0 :(得分:8)
您应该使用@XmlElementWrapper Annotation。它们用于生成Collections
为ArrayList
定义一个包装器,如下所示
class ListWrapper {
@XmlElementWrapper(name = "wrapperList")
private List<String> list;
public void setList(List<String> list) {
this.list = list;
}
}
在BoxItem
班级
@XmlElementWrapper(name = "integerMap")
Map<Integer, ListWrapper> intgerStringArrMap;
这是完整的课程。
@XmlRootElement
public class BoxItem {
@XmlElementWrapper(name = "integerMap")
Map<Integer, ListWrapper> intgerStringArrMap;
BoxItem() {
intgerStringArrMap = new HashMap<Integer, ListWrapper>();
for (int i = 0; i < 2; i++) {
ArrayList<String> stringArrayList = new ArrayList<String>();
ListWrapper wrapper = new ListWrapper();
wrapper.setList(stringArrayList);
for (int j = 0; j < 2; j++) {
stringArrayList.add("2");
}
intgerStringArrMap.put(i, wrapper);
}
}
public static void main(String[] args) throws JAXBException {
BoxItem box = new BoxItem();
JAXBContext jc = JAXBContext.newInstance(BoxItem.class);
jc.createMarshaller().marshal(box, System.out);
}
}
class ListWrapper {
@XmlElementWrapper(name = "wrapperList")
private List<String> list;
public void setList(List<String> list) {
this.list = list;
}
}
运行上面的内容应该得到以下输出,
<boxItem>
<integerMap>
<entry>
<key>0</key>
<value>
<wrapperList>
<list>2</list>
<list>2</list>
</wrapperList>
</value>
</entry>
<entry>
<key>1</key>
<value>
<wrapperList>
<list>2</list>
<list>2</list>
</wrapperList>
</value>
</entry>
</integerMap>
</boxItem>
答案 1 :(得分:0)
XmlAdapter
这样的案例。
请参阅How to marshall Map<String, List<Objects>> using JAXB以编写您自己的XmlAdapter