我是SimpleXML的新手,我认为它声称能够做到这一点,所以我肯定做错了什么。也许你能帮我。
问题是,如果我有一个父对象,它有两个指向同一个子对象的链接,当父对象被反序列化时,我现在有两个链接指向相同但不同的对象(内存中的不同位置)。这会破坏结构。
以下是我正在做的:
主题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;
}
}
[...]
火花.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是不同的对象。是否有方法将它们反序列化为同一对象?我来自iOS,那里的系统神奇地工作;似乎Android上也应该有类似的东西;也许SimpleXML不是它。
提前感谢!