简体   繁体   English

使用DataContractSerializer序列化,但不能反序列化

[英]Using DataContractSerializer to serialize, but can't deserialize back

I have the following 2 functions: 我有以下两个功能:

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);
}

The first one seems to serialize an object to an xml string just fine. 第一个似乎将对象序列化为xml字符串就好了。 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. XML显示有效,没有损坏的标记,开头或结尾没有空格等。现在第二个函数不希望将我的xml字符串反序列化回对象。 On the last line I get: 在最后一行我得到:

There was an error deserializing the object of type [MY OBJECT TYPE HERE]. 反序列化[MY OBJECT TYPE HERE]类型的对象时出错。 The data at the root level is invalid. 根级别的数据无效。 Line 1, position 1. 第1行,第1位。

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. 我尝试重写Deserialize函数几次,它似乎总是出现同样的错误。 Thank you! 谢谢!

Oh, and this is how I'm calling the 2 functions: 哦,这就是我调用2个函数的方式:

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

Here is how I've always done it: 以下是我一直这样做的方式:

    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);
        }
    }

Other solution is: 其他解决方案是:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains eg: 一句话:有时会发生原始xml包含例如:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples.. 那么你当然不能使用其他例子中使用的UTF8编码。

I ended up doing the following and it works. 我最终做了以下工作。

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). 调用stream.GetBuffer()时,似乎主要问题出在Serialize函数中。 Calling stream.ToArray() appears to work. 调用stream.ToArray()似乎工作。

This best for XML Deserialize 这最适合XML反序列化

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM