Over a million developers have joined DZone.

Using the DataContractSerializer to Serialize and Deserialize

· Big Data Zone

Hortonworks DataFlow is an integrated platform that makes data ingestion fast, easy, and secure. Download the white paper now.  Brought to you in partnership with Hortonworks

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);

            }

        }

Hortonworks Sandbox is a personal, portable Apache Hadoop® environment that comes with dozens of interactive Hadoop and it's ecosystem tutorials and the most exciting developments from the latest HDP distribution, brought to you in partnership with Hortonworks.

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 }}