起初:对不起,如果这是一个冗长且代码繁重的问题。我正在尝试序列化和反序列化一个名为level的类,如下所示:
[DataContract]
public class Level
{
[DataMember]
public List<Face> faces;
public Level()
{
Face a = new Face();
Face b = new Face();
Face c = new Face();
Face d = new Face();
a.edges.Add(new Edge(b, c));
b.edges.Add(new Edge(a, c));
c.edges.Add(new Edge(a, d));
d.edges.Add(new Edge(a, b));
this.faces = new List<Face>() { a, b, c, d };
}
}
[DataContract(IsReference = true)]
public class Face
{
[DataMember]
public List<Edge> edges;
public Face()
{
this.edges = new List<Edge>();
}
}
[DataContract(IsReference = true)]
public class Edge
{
[DataMember]
public Face a;
[DataMember]
public Face b;
public Edge(Face a, Face b)
{
this.a = a;
this.b = b;
}
}
因为有循环引用我需要启用datacontract序列化器的引用功能。但是当我运行这个时我得到错误
SerializationException:找不到引用ID为'i1'的反序列化对象
serialize和deserialize函数如下所示:
// object to be serialized
public Level level;
public void Serialize()
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Level));
FileStream stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Create);
Debug.Log("serial");
serializer.WriteObject(stream, level);
stream.Close();
}
// function to serialize an object to a json text file
public void Deserialize()
{
FileStream stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Open);
DataContractSerializer serializer = new DataContractSerializer(typeof(Level));
Level loaded = (Level)serializer.ReadObject(stream);
stream.Close();
}
void Start()
{
level = new Level();
Serialize();
Deserialize();
}
这里也是一个序列化的xml示例:
<Level xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/">
<faces>
<Face z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<edges>
<Edge z:Id="i2">
<a z:Id="i3">
<edges>
<Edge z:Id="i4">
<a z:Ref="i1" />
<b z:Id="i5">
<edges>
<Edge z:Id="i6">
<a z:Ref="i1" />
<b z:Id="i7">
<edges>
<Edge z:Id="i8">
<a z:Ref="i1" />
<b z:Ref="i3" />
</Edge>
</edges>
</b>
</Edge>
</edges>
</b>
</Edge>
</edges>
</a>
<b z:Ref="i5" />
</Edge>
</edges>
</Face>
<Face z:Ref="i3" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" />
<Face z:Ref="i5" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" />
<Face z:Ref="i7" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" />
</faces>
</Level>
我现在搜索了几天的答案,但仍然没有得到任何结果。 你能告诉我如何解决这个问题吗?
答案 0 :(得分:0)
我认为您的问题可能是您尝试反序列化之前序列化的内容,然后将IsReference=true
参数添加到属性中。
如果删除测试文件并使用更新后的代码创建一个新文件,则反序列化过程应该没有问题。