Over a million developers have joined DZone.
Platinum Partner

Using the DataContractSerializer to Serialize and Deserialize

· Big Data Zone

The Big Data Zone is brought to you in partnership with Hortonworks.  Learn more about Connected Data Platforms that power the creation of modern data applications and how they deliver actionable intelligence. 

To serialize a Business object marked with [DataContract] and properties marked with [DataMember] attributes…

public static string DataContractSerializeObject<T>(T objectToSerialize)

        {

using (var output = new StringWriter())

            {

using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })

                {

var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);

                    dataContractSerializer.WriteObject(writer, objectToSerialize);

return output.GetStringBuilder().ToString();

                }

            }

        }

Then to deserialize back to your DataContract type, use this logic…

public static T Deserialize<T>(string xml)

        {

using (Stream stream = new MemoryStream())

            {

byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);

                stream.Write(data, 0, data.Length);

                stream.Position = 0;

var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);

return (T)dataContractSerializer.ReadObject(stream);

            }

        }

The Big Data Zone is brought to you in partnership with Hortonworks.  Learn, Collaborate, and Thrive with Hortonworks Community Connection

Topics:
dotnet,how-to,tools,visual studio,data access,.net & windows,c-sharp,serialization

Published at DZone with permission of Merrick Chaffer , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}