序列化和反序列化

时间:2012-06-26 15:48:20

标签: .net serialization

我使用http://www.codeproject.com/Articles/10429/Convert-XML-data-to-object-and-back-using-serializ作为建议的基础序列化了一个对象并获得了XML。我将XML存储在2008数据库的文本字段中。当我反序列化它时,我得到InvalidOperationException。任何人都有过对一个物体进行反序列化并且首先发现其严重序列化的经验吗?

public static Request ToObject(string xml)
    {
        StringReader stream = null;
        XmlTextReader reader = null;
        try
        {
            // serialise to object
            XmlSerializer serializer = new XmlSerializer(typeof(Request));
            stream = new StringReader(xml); // read xml data
            reader = new XmlTextReader(stream);  // create reader
            // covert reader to object
            return (Request)serializer.Deserialize(reader);
        }
        catch
        {
            return null;
        }
        finally
        {
            if (stream != null) stream.Close();
            if (reader != null) reader.Close();
        }
    }

    public static string ToXML(Request oRequest)
    {
        MemoryStream stream = null;
        TextWriter writer = null;
        try
        {
            stream = new MemoryStream(); // read xml in memory
            writer = new StreamWriter(stream, Encoding.Unicode);
            // get serialise object
            XmlSerializer serializer = new XmlSerializer(typeof(Request));
            serializer.Serialize(writer, oRequest); // read object
            int count = (int)stream.Length; // saves object in memory stream
            byte[] arr = new byte[count];
            stream.Seek(0, SeekOrigin.Begin);
            // copy stream contents in byte array
            stream.Read(arr, 0, count);
            UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
            return utf.GetString(arr).Trim();
        }
        catch
        {
            return string.Empty;
        }
        finally
        {
            if (stream != null) stream.Close();
            if (writer != null) writer.Close();
        }
    }

1 个答案:

答案 0 :(得分:1)

This应该回答你的问题。

简而言之,您使用Unicode进行序列化,但不反序列化。

所以你的修复是 - 在ToObject方法中,改变:

MemoryStream stream;
stream = new MemoryStream(Encoding.Unicode.GetBytes(xml));