Node オブジェクトのツリーをシリアライズおよびデシリアライズしようとしています。抽象「Node」クラスと、そこから派生する他の抽象クラスおよび具象クラスは、「Informa」プロジェクトで定義されています。さらに、Informa でシリアライゼーション/デシリアライゼーション用の静的クラスを作成しました。
まず、ツリーをDictionary(guid,Node)型のフラット リストに分解します。ここで、guid は Node の一意の ID です。
問題なくすべてのノードをシリアル化できます。しかし、逆シリアル化しようとすると、次の例外が発生します。
行 1 位置 227 のエラー。要素 ' http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value ' には、'Informa:Building' データ コントラクトのデータが含まれています。デシリアライザーには、このコントラクトにマップされる型の知識はありません。'Building' に対応する型を既知の型のリストに追加します。たとえば、KnownTypeAttribute を使用するか、DataContract シリアライザーに渡される既知の型のリストに追加します。
Building を含む Node から派生するすべてのクラスには、[KnownType(typeof(type t))]属性が適用されます。
私のシリアライゼーションとデシリアライゼーションの方法は次のとおりです。
public static void SerializeProject(Project project, string filePath)
{
try
{
Dictionary<Guid, Node> nodeDic = DeconstructProject(project);
Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
//serialize
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>),"InformaProject","Informa");
ser.WriteObject(stream,nodeDic);
// Cleanup
stream.Close();
}
catch (Exception e)
{
MessageBox.Show("There was a problem serializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw e;
}
}
public static Project DeSerializeProject(string filePath)
{
try
{
Project proj;
// Read the file back into a stream
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>), "InformaProject", "Informa");
Dictionary<Guid, Node> nodeDic = (Dictionary<Guid, Node>)ser.ReadObject(stream);
proj = ReconstructProject(nodeDic);
// Cleanup
stream.Close();
return proj;
}
catch (Exception e)
{
MessageBox.Show("There was a problem deserializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}