2012-06-26 288 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));