Как сериализовать ArrayList в XML с помощью XStream? - PullRequest
0 голосов
/ 24 апреля 2018

Я пытаюсь сериализовать ArrayList пользовательских объектов в XML с использованием XStream, но я получаю некоторые странные результаты для вывода.

Вот код, который я использую для преобразования,

public void save (String fileName) {

    /* 1. Initialize the serializer. */
    XStream xstream = new XStream(new DomDriver());

    /* 2. Generate the XML string. */
    String xml = xstream.toXML(application.getShapes());

    /* 3. Print the XML string into a file with the given file name. */
    try {
        PrintWriter writer = new PrintWriter(fileName);
        writer.write(xml);
        writer.close();
    } catch (Exception ex) {
        ex.getMessage();
    }
}

и вот ArrayList, который я хочу сериализовать,

/* List of all the shapes drawn on the canvas. */
private ArrayList<Shape> shapes;

и вот вызов метода save,

public void saveClicked() {

    application.setSaveNLoadstrategy(new XmlStrategy());
    application.save("drawing.xml");
}

и, наконец, вот вывод, который я получаю в файле XML,

<list>
<model.Shape>
<application>
  <canvas>
    <dirtyBits>0</dirtyBits>
    <__geomBounds class="com.sun.javafx.geom.RectBounds">
      <minX>0.0</minX>
      <maxX>564.0</maxX>
      <minY>0.0</minY>
      <maxY>200.0</maxY>
    </__geomBounds>
    <__txBounds class="com.sun.javafx.geom.RectBounds">
      <minX>18.0</minX>
      <maxX>582.0</maxX>
      <minY>100.0</minY>
      <maxY>300.0</maxY>
    </__txBounds>
    <pendingUpdateBounds>false</pendingUpdateBounds>
    <parent class="javafx.scene.Node$1">
      <value class="javafx.scene.layout.Pane">
        <dirtyBits>1024</dirtyBits>
        <__geomBounds class="com.sun.javafx.geom.RectBounds">
          <minX>0.0</minX>
          <maxX>812.0</maxX>
          <minY>0.0</minY>
          <maxY>400.0</maxY>
        </__geomBounds>
        <__txBounds class="com.sun.javafx.geom.RectBounds">
          <minX>0.0</minX>
          <maxX>812.0</maxX>
          <minY>0.0</minY>
          <maxY>400.0</maxY>
        </__txBounds>
        <pendingUpdateBounds>false</pendingUpdateBounds>
        <parentDisabledChangedListener class="null"/>
        <parentTreeVisibleChangedListener class="null"/>
        <scene>
          <value class="javafx.scene.Scene">
            <widthSetByUser>600.0</widthSetByUser>
            <heightSetByUser>400.0</heightSetByUser>

Имейте в виду, что размер выходного XML-файла на удивление составляет 64 МБ, поэтому я просто добавил несколько строк!

1 Ответ

0 голосов
/ 24 апреля 2018

Как вы говорите, кажется, что вы сериализуете весь холст.

Я провел несколько тестов с кодом ниже:

package xStream;

import java.awt.Shape;
import java.awt.geom.Arc2D;
import java.io.PrintWriter;
import java.util.ArrayList;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class application {

    /* List of all the shapes drawn on the canvas. */
    private static ArrayList<Shape> shapes = new ArrayList<Shape>();


    public static void save (String fileName) {

        /* 1. Initialize the serializer. */
        XStream xstream = new XStream(new DomDriver());

        /* 2. Generate the XML string. */
        String xml = xstream.toXML(shapes);

        /* 3. Print the XML string into a file with the given file name. */
        try {
            PrintWriter writer = new PrintWriter(fileName);
            writer.write(xml);
            writer.close();
        } catch (Exception ex) {
            ex.getMessage();
        }
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        shapes.add(new Arc2D.Double(100,100,10,10,0,90, Arc2D.CHORD));
        shapes.add(new Arc2D.Double(100,100,10,10,0,180, Arc2D.CHORD));

        application.save("drawing.xml");
        System.exit(0);
    }

}

и получил результат:

<list>
  <java.awt.geom.Arc2D_-Double serialization="custom">
    <unserializable-parents>
      <type>1</type>
    </unserializable-parents>
    <java.awt.geom.Arc2D_-Double>
      <default>
        <extent>90.0</extent>
        <height>10.0</height>
        <start>0.0</start>
        <width>10.0</width>
        <x>100.0</x>
        <y>100.0</y>
      </default>
      <byte>1</byte>
    </java.awt.geom.Arc2D_-Double>
  </java.awt.geom.Arc2D_-Double>
  <java.awt.geom.Arc2D_-Double serialization="custom">
    <unserializable-parents>
      <type>1</type>
    </unserializable-parents>
    <java.awt.geom.Arc2D_-Double>
      <default>
        <extent>180.0</extent>
        <height>10.0</height>
        <start>0.0</start>
        <width>10.0</width>
        <x>100.0</x>
        <y>100.0</y>
      </default>
      <byte>1</byte>
    </java.awt.geom.Arc2D_-Double>
  </java.awt.geom.Arc2D_-Double>
</list>

Что я считаю хорошим.

David

...