Using the DataContractSerializer to Serialize and Deserialize
Join the DZone community and get the full member experience.
Join For FreeTo 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); } }
Property (programming)
Object (computer science)
Published at DZone with permission of Merrick Chaffer, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments