0

我正在尝试学习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 的副本。有什么帮助吗?

4

1 回答 1

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
于 2012-10-20T02:13:29.690 回答