14 June 2010

Data Contract Serializer

The DataContractSerializer class serializes and deserializes an instance of a type stream or document using a supplied data contract.
The class to be serialized must be marked with the DataContractAttribute attribute.
Properties and fields of the class that are to be serialized must be marked with the DataMemberAttribute.

The DataContractSerializer WriteObject and ReadObject can then be used for serialization / deserialization.

Example:
1) Serialization

MyType myType = new MyType();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyType));
MemoryStream ms = new MemoryStream();
dcs.WriteObject(ms, myType);

string result = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);

2) Deserialization


MyType myType = null;

DataContractSerializer dcs = new DataContractSerializer(typeof(MyType));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(EncodedString));
myType = (MyType)dcs.ReadObject(ms);


Where the EncodedString is the encoded string to decode (result from step 1)

No comments: