0

我已经使用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();
        }
    }
4

1 回答 1

1

应该回答你的问题。

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

所以你的解决方法是 - 在 ToObject 方法中,更改:

MemoryStream stream;
stream = new MemoryStream(Encoding.Unicode.GetBytes(xml));
于 2012-06-26T16:30:06.723 回答