0

I have serialised an object using http://www.codeproject.com/Articles/10429/Convert-XML-data-to-object-and-back-using-serializ as a basis for advice and got the XML. I stored the XML in a text field in a 2008 database. When I deserialize it, I get InvalidOperationException. Any had experience of deserialising an object and finding out its badly serialized in the first place?

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();
        }
    }
MiscellaneousUser
  • 2,915
  • 4
  • 25
  • 44

1 Answers1

1

This should answer your question.

In short, you are using Unicode to serialize, but not deserialize.

So your fix is - In the ToObject Method, change:

MemoryStream stream;
stream = new MemoryStream(Encoding.Unicode.GetBytes(xml));
Community
  • 1
  • 1
T.Coutlakis
  • 2,436
  • 1
  • 19
  • 19