【发布时间】:2011-06-27 23:13:02
【问题描述】:
我有以下两个功能:
public static string Serialize(object obj)
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}
public static object Deserialize(string xml, Type toType)
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
// memoryStream.Position = 0L;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer dataContractSerializer = new DataContractSerializer(toType);
return dataContractSerializer.ReadObject(reader);
}
第一个似乎可以将对象序列化为 xml 字符串。 XML 看起来有效,没有损坏的标签,开头或结尾没有空格等。现在第二个函数不想将我的 xml 字符串反序列化回对象。在我得到的最后一行:
反序列化时出错 [MY OBJECT TYPE HERE] 类型的对象。 根级别的数据无效。 第 1 行,位置 1。
我做错了什么?我尝试重写 Deserialize 函数几次,它似乎总是同一种错误。谢谢!
哦,这就是我调用这两个函数的方式:
SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));
【问题讨论】:
标签: c# c#-4.0 xml-serialization datacontractserializer