处理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