我有一个要整理的物体。

@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>

如何将MapList中ArrayList内部的元素编码?

最佳答案

您应该使用@XmlElementWrapper注释。它们用于围绕Collections产生包装XML元素

为您的ArrayList定义一个包装器,如下所示,

class ListWrapper {

    @XmlElementWrapper(name = "wrapperList")
    private List<String> list;

    public void setList(List<String> list) {
        this.list = list;
    }
}

BoxItem类中如下定义 map ,
@XmlElementWrapper(name = "integerMap")
Map<Integer, ListWrapper> intgerStringArrMap;

这是完整的类(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;
    }
}

运行上面的命令应获得以下输出,
<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>

08-03 17:34