XStream.fromXML列表生成空列表

时间:2012-10-20 01:39:35

标签: java xstream

我正在尝试学习XStream,并且我已经遵循API以及我能理解它,但以下代码片段

List<Rectangle> rectangleArray = new ArrayList<Rectangle>();
xstream = new XStream(new DomDriver());
List<Rectangle> rectangleArray2 = new ArrayList<Rectangle>();

rectangleArray.add(new Rectangle(18,45,2,6));
String xml = xstream.toXML(rectangleArray);
System.out.println(xml);
xstream.fromXML(xml, rectangleArray2);
System.out.println("new list size: " + rectangleArray2.size());

产生输出

<list>
    <java.awt.Rectangle>
    <x>18</x>
    <y>45</y>
    <width>2</width>
    <height>6</height>
    </java.awt.Rectangle>
</list>
new list size: 0

我无法弄清楚为什么rectangleArray2现在不是rectangleArray的副本。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

通过List处理XStream有点棘手。要处理列表,您需要定义一个包装类来保存列表,例如:

    public class RectangleList {

        private List<Rectangle> rectangles = new ArrayList<Rectangle>();

        public List<Rectangle> getRectangles() {
            return rectangles;
        }

        public void setRectangles(List<Rectangle> rectangles) {
            this.rectangles = rectangles;
        }
    }

然后将alias列表添加到RectangleList

      xstream.alias("list", RectangleList.class);

并注册隐式转换器以管理列表:

     xstream.addImplicitCollection(RectangleList.class, "rectangles"); 

如果您希望<java.awt.Rectangle>打印为<rectangle>,请按以下方式注册别名:

     xstream.alias("rectangle", Rectangle.class);

现在使用RectangleList类进行转换,它应该可以正常工作。

最终测试代码如下:

    RectangleList recListInput = new RectangleList();
    RectangleList recListOutput = new RectangleList();
    XStream xstream = new XStream(new DomDriver());
    xstream.alias("list", RectangleList.class);
    xstream.alias("rectangle", Rectangle.class);
    xstream.addImplicitCollection(RectangleList.class, "rectangles");

    ArrayList<Rectangle> rectangleArray = new ArrayList<Rectangle>();
    rectangleArray.add(new Rectangle(18,45,2,6));
    recListInput.setRectangles(rectangleArray);
    String xml = xstream.toXML(rectangleArray);
    System.out.println(xml);
    xstream.fromXML(xml, recListOutput);
    System.out.println("new list size: " + recListOutput.getRectangles().size());

这将输出打印为:

    <list>
      <rectangle>
        <x>18</x>
        <y>45</y>
        <width>2</width>
        <height>6</height>
      </rectangle>
    </list>
    new list size: 1