I have an object i'd like to marshall.
@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);
}
}
}
Now let's assume we have a boxItem = new BoxItem()
If i call jaxbMarshaller.marshal(boxItem, System.out);, the values are empty for each entry.
<?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>
How to marshall the elements inside the ArrayList in a Map value?
You should use @XmlElementWrapper Annotation.They are used to produce a wrapper XML element around Collections
Define a wrapper for your ArrayList
like below,
class ListWrapper {
@XmlElementWrapper(name = "wrapperList")
private List<String> list;
public void setList(List<String> list) {
this.list = list;
}
}
Define your Map as below in BoxItem
class,
@XmlElementWrapper(name = "integerMap")
Map<Integer, ListWrapper> intgerStringArrMap;
Here is the complete class.
@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;
}
}
Running the above should get the below output,
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With