.NET Zone is brought to you in partnership with:

Merrick Chaffer is a Software Developer with Russell Reynolds Associates, with over 16 years experience in areas relating to Microsoft Application Development. Merrick is a DZone MVB and is not an employee of DZone and has posted 37 posts at DZone. You can read more from them at their website. View Full User Profile

Using the DataContractSerializer to Serialize and Deserialize

12.14.2013
| 6814 views |
  • submit to reddit

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

            }

        }
Published at DZone with permission of Merrick Chaffer, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)