DataContractSerializer made its first appearance with release of WCF but can operate outside WCF.
DataContractSerializer can serialize types decorated with DataContract, MessageContract, Serializable attributes, types that implement IXmlSerialisable and all public types without Attributes.
During serialization Reference integrity is by default not preserved. You can preserve it by setting “IsReference = true” to DataContract attribute. Note that this approach my cause problems if DataContractSerializer is not serializer who will deserialize data.
1 |
[DataContract(IsReference = true)] |
You can also use OnSerializing, OnSerialized, OnDeserializing, OnDeserialized Attributes to fine-grain your serialization process.
This tutorial will explain how to serialize and deserialize types by decorating type with DataContract attribute.
First we use need to add reference to System.Runtime.Serialization. Secondly we decorate the type with DataContract Attribute, and inside type wee decorate fields and properties with DataMember Attribute. Then we instantiate DataContractSerializer instance and use its WriteObject and ReadObject methods to serialize/deserialize data.
Example of DataContractSerializer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
using System; using System.Runtime.Serialization; using System.IO; using System.Xml.Linq; namespace DataContractSerializerExample { class Program { static void Main(string[] args) { // Choose between types to serialize Employee employee = new Employee() { _employeeId = 1, employeeName = "JohnDoe", _employeeDepartment = new Department() { _departmentId = 1, _departmentName = "Sales" } }; ClubActivity activity = new ClubActivity() { _employeeId = 1, employeeName = "JohnDoe", ActivityName = "Gym", _employeeDepartment = new Department() { _departmentId = 1, _departmentName = "Sales" } }; // We will be reading data from the memory // so it is best to use Memory stream. MemoryStream memoryStream = new MemoryStream(); //Lets start by Serializing data. // both ClubActivity and Employee classes are provided // as parameters so you can experiment // in SerializeData Method Stream stream = SerializeData(employee, activity, memoryStream); DisplaySerializationResultInConsole(stream); //stream.Position = 0; //And now lets deserialize data Deserialize(stream); Console.ReadKey(); } private static Stream SerializeData(Employee employee, ClubActivity activity, MemoryStream memoryStream) { // Note that we needed to supply Type information to constructor // Reason is that type and Assembly information are not serialized DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Employee)); // WriteObject method is responsible for serialization itself dataContractSerializer.WriteObject(memoryStream, activity); // It is best to rewind stream to 0 position now // so consumer of of stream can consume it right away. memoryStream.Position = 0; //// Uncomment bottom line //// to see the result of serialization //DisplaySerializationResultInConsole(memoryStream); // Stream is ready to be transmitted // So lets send it. return memoryStream; } private static void Deserialize(Stream stream) { // If you have serialized data by supplying // Employee type to constructor, change // type in next line // Lets start Deserialization process by instantiating DataContractSerializer DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Employee)); // ReadObject method is responsible for Deserialization object employeeObject = dataContractSerializer.ReadObject(stream); // As you can see Club activity object has been deserialized ClubActivity oldEmployee = employeeObject as ClubActivity; // Proof of Deserialization result: Console.WriteLine("Deserialization result: Employee id:{0}, Employee name: {1}, Department id: {2}, Department name: {3}, Club Activity: {4}", oldEmployee._employeeId, oldEmployee.employeeName, oldEmployee._employeeDepartment._departmentId, oldEmployee._employeeDepartment._departmentName, oldEmployee.ActivityName); // Uncomment this line // if you have serialized Employee class //Console.WriteLine("Deserialization result: Employee id:{0}, Employee name: {1}, Department id: {2}, Department name: {3}", oldEmployee._employeeId, oldEmployee.employeeName, oldEmployee._employeeDepartment._departmentId, oldEmployee._employeeDepartment._departmentName); } private static void DisplaySerializationResultInConsole(Stream stream) { string streamResult= new StreamReader(stream).ReadToEnd(); string readableXml = MoreReadableXml(streamResult); Console.WriteLine(readableXml); stream.Position = 0; } static string MoreReadableXml(string xml) { XDocument doc = XDocument.Parse(xml); return doc.ToString(); } } [DataContract, KnownType(typeof(ClubActivity))] public class Employee { [DataMember] public int _employeeId; [DataMember] public string employeeName { get; set; } [DataMember] public Department _employeeDepartment; } [DataContract] public class ClubActivity : Employee { [DataMember] public string ActivityName { get; set; } } [DataContract] public class Department { [DataMember] public int _departmentId; [DataMember] public string _departmentName; } } |
By using DataMember Attribute we can serialize automatic properties, because property itself will be serialized and not its backing field.
Because DataContractSerializer does not store type and assembly information we need to tell it which is the type we wish to serialize by specifying type in the DataContractSerializer constructor.
As no type or assembly information are preserved be sure to supply KnownType Attribute to your base class to be able to use inheritance properly.

Data Contract Serializer
You can download solution from this link.
To return to other serialization techniques return to this location.