【发布时间】:2018-04-16 20:58:30
【问题描述】:
首先:对不起,如果这是一个冗长且代码繁重的问题。我正在尝试序列化和反序列化一个名为 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;
}
}
由于存在循环引用,我需要启用数据合同序列化程序的引用功能。但是当我运行它时,我得到了错误
SerializationException:未找到引用 ID 为“i1”的反序列化对象
序列化和反序列化函数如下所示:
// 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>
我已经搜索了几天的答案,但仍然没有得到任何接近。 请给我一个关于如何解决这个问题的提示吗?
【问题讨论】:
-
此处的代码看起来完全相关且恰当 - 不要道歉!
-
我用你的代码试过了,效果很好;看一下xml示例
-
当我使用您的示例 xml 运行
Deserialize()时:它工作正常。你的目标是什么平台? -
我在游戏引擎中运行这个。如果它对你有用,问题可能出在团结上。如果是这样,我很高兴您对此进行了测试并将代码排除为错误源。
-
如果你的目标是统一,DCS 的工作方式可能会有所不同......遗憾的是我没有“统一”,所以我很难在那里测试它,抱歉
标签: c# serialization deserialization