如何使用SimpleXML保持序列化的结构?

时间:2015-08-14 18:01:33

标签: java xml-parsing xml-serialization xml-deserialization simple-framework

我是SimpleXML的新手,我认为它声称能够做到这一点,所以我一定做错了。也许你可以帮助我。

问题是如果我有一个父对象有两个指向同一子对象的链接,当父对象被反序列化时,我现在有两个链接指向相同但不同的对象(内存中的不同位置)。这打破了结构。

以下是我正在做的事情:

Topic.java:

@Root (name = "Topic")
public class Topic {

    @Attribute (name = "name")
    String name = null;

    @Element (name = "id")
    int id = -1;

    @ElementList (name = "sparks")
    ArrayList<Spark> sparks = null;

    public Topic(
            @Attribute (name = "name") String inName,
            @Element (name = "id") int inID,
            @ElementList (name = "sparks") ArrayList<Spark> inSparks) {
        name = new String(inName);
        id = inID;
        if (inSparks == null) {
            sparks = new ArrayList<>(50);
        } else {
            sparks = inSparks;
        }
    }
[...]

Spark.java

@Root (name = "Spark")
public class Spark {

    @Element (name = "text", required = false)
    String text = null;

    @Element (name = "dateCompleted", required = false)
    Date dateCompleted = null;

    @Element (name = "rejected")
    boolean rejected = false;

    @Element (name = "delayedUntil", required = false)
    Date delayedUntil = null;

    @Attribute (name = "id")
    int id = -1; 

    @Element (name = "packName", required = false)
    String packName = null;

    public Spark(
            @Element (name = "text") String inText,
            @Attribute (name = "id") int inID,
            @Element (name = "packName") String inPackName) {
        text = new String(inText);
        id = inID;
        packName = new String(inPackName);
    }

    [...]

演示问题:

    Serializer serializer = new Persister();
    File saveFile = new File(this.getFilesDir(), "test.xml");

    Topic testTopic = new Topic("TestTopic", 1);
    Spark newSpark = new Spark ("This is the sample text.", 1, "PretendPack");
    testTopic.sparks.add(newSpark);
    testTopic.sparks.add(newSpark);

    try {
        serializer.write(testTopic, saveFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Topic newTopic = null;
    try {
        newTopic = serializer.read(Topic.class, saveFile);
    } catch (Exception e) {
        Log.e("IntimacyToolbox", "Was unable to deserialize from the savedData.");
        e.printStackTrace();
    }
    Spark spark1 = newTopic.sparks.get(0);
    Spark spark2 = newTopic.sparks.get(1);
    if (spark1 == spark2) {
        Log.d("IntimacyToolbox", "Good: sparks are the same.");
    } else {
        Log.d("IntimacyToolbox", "Bad: sparks are different objects.");
    }

运行这段代码后,newTopic.sparks ArrayList中的两个spark是不同的对象。有没有办法让它们反序列化为同一个对象?我来自iOS,那里的系统神奇地起作用;似乎在Android上应该有类似的东西;也许SimpleXML不是它。

提前致谢!

1 个答案:

答案 0 :(得分:1)

是的,请使用CycleStrategy。