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

処理ListXStream少し注意が必要です。リストを処理するには、リストを保持するラッパークラスを定義する必要があります。例:

    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>、以下のようにansエイリアスを登録します。

     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 に答える