2012-06-26 351 views
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(); 
     } 
    } 

回答

1

This應該回答你的問題。

總之,您使用Unicode來序列化,但不是反序列化。

所以你的解決方法是 - 在ToObject方法,變化:

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