[c#] Using DataContractSerializer to serialize, but can't deserialize back

I have the following 2 functions:

public static string Serialize(object obj)
{
    DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
    MemoryStream memoryStream = new MemoryStream();
    serializer.WriteObject(memoryStream, obj);
    return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}

public static object Deserialize(string xml, Type toType)
{
    MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
   // memoryStream.Position = 0L;
    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
    DataContractSerializer dataContractSerializer = new DataContractSerializer(toType);
    return dataContractSerializer.ReadObject(reader);
}

The first one seems to serialize an object to an xml string just fine. The XML appears valid, no broken tags, no white spaces at the beginning or at the end, etc. Now the second function doesn't want to deserialize my xml string back to the object. On the last line I get:

There was an error deserializing the object of type [MY OBJECT TYPE HERE]. The data at the root level is invalid. Line 1, position 1.

What am I doing wrong? I tried rewriting the Deserialize function a few times, and it always seems to be the same kind of error. Thank you!

Oh, and this is how I'm calling the 2 functions:

SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));

This question is related to c# c#-4.0 xml-serialization datacontractserializer

The answer is


I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.


Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..


This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to c#-4.0

Xml Parsing in C# EPPlus - Read Excel Table How to add and get Header values in WebApi How to make all controls resize accordingly proportionally when window is maximized? How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project How to get first record in each group using Linq How to get first object out from List<Object> using Linq ASP.Net MVC - Read File from HttpPostedFileBase without save .NET NewtonSoft JSON deserialize map to a different property name Datetime in C# add days

Examples related to xml-serialization

Serialize Property as Xml Attribute in Element Reading from memory stream to string There is an error in XML document (1, 41) Xml serialization - Hide null values Using DataContractSerializer to serialize, but can't deserialize back Serialize an object to XML Serializing an object as UTF-8 XML in .NET Convert XML String to Object Serialize an object to string Using StringWriter for XML Serialization

Examples related to datacontractserializer

Using DataContractSerializer to serialize, but can't deserialize back When to use DataContract and DataMember attributes?