使用DataContractserialiser进行字典序列化

时间:2012-05-10 11:42:58

标签: c# xml serialization dictionary

我的方法返回Dictionary<TZerokey, Dictionary<TFirstKey, Dictionary<TSecondKey,Dictionary<TThirdKey,TValue>>>>,我将使用DataContractSerialiser将此对象序列化/反序列化为XML。

以下是我的方法:

public static void SerializeDictionaryToXml<T>(this T obj, string fileName)
{
    DataContractSerializer ser = new DataContractSerializer(typeof(T));
    // System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
    FileStream fileStream = new FileStream(fileName, FileMode.Create);
    ser.WriteObject(fileStream, obj);
    fileStream.Close();
}

public static T DeserializeDictionaryFromXml<T>(string xml)
{
    FileStream fs = new FileStream(xml,
    FileMode.Open);
    XmlDictionaryReader reader =    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
    DataContractSerializer ser = new DataContractSerializer(typeof(T));

    // Deserialize the data and read it from the instance.
    T deserializedObject = (T)ser.ReadObject(reader, true);
    reader.Close();
    fs.Close();

    return deserializedObject;
}

代码运行正常,但我没有得到预期的输出。有人能看出我做错了吗?

0 个答案:

没有答案