使用 DataContractSerializer 进行序列化,但无法反序列化回来 [英] Using DataContractSerializer to serialize, but can't deserialize back

查看:36
本文介绍了使用 DataContractSerializer 进行序列化,但无法反序列化回来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个功能:

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 字符串反序列化回对象.在最后一行我得到:

The first one seems to serialize an object to an xml string just fine. The XML appears valid, no broken tags, no white spaces at the beginning or at the end, etc. Now the second function doesn't want to deserialize my xml string back to the object. On the last line I get:

反序列化时出错[此处为我的对象类型] 类型的对象.根级别的数据无效.第 1 行,位置 1.

There was an error deserializing the object of type [MY OBJECT TYPE HERE]. The data at the root level is invalid. Line 1, position 1.

我做错了什么?我尝试了几次重写 Deserialize 函数,它似乎总是同一种错误.谢谢!

What am I doing wrong? I tried rewriting the Deserialize function a few times, and it always seems to be the same kind of error. Thank you!

哦,这就是我调用这两个函数的方式:

Oh, and this is how I'm calling the 2 functions:

SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));

推荐答案

我一直都是这样做的:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

这篇关于使用 DataContractSerializer 进行序列化,但无法反序列化回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆