Windows Phone 7 Serialization: DataContract Serialization

In this post I am going to continue studying the ways how to serialize objects in Windows Phone 7 applications. This time I will explain DataContract Serialization using DataContractSerializer class. This type of serialization can also be applied to Silverlight applications.

Additional Information

Adding a reference

Keep in mind that DataContractSerializer requires System.Runtime.Serialization namespace to be added to project. To do so right click the project name and choose Add Reference there. Select System.Runtime.Serialization namespace on .NET tab (check image bellow).


eugenedotnet add system runtime serialization namespace for data contract serialization


Creating a sample class

I am going to use almost the same class I’ve created for the XmlSerializer tutorial, but slightly modified. To allow object to be serialized using DataContract serialization you have to add DataContractAttribute to the class (public class). XML Generation can be controlled using DataMemberAttribute for those properties that need to be serialized and IgnoreDataMemberAttribute for those properties that need to be ignored during serialization. Public properties will be automatically exposed. Take a look at example bellow.

[DataContractAttribute]
public class SampleData
{
    [DataMember]
    public string ContentText { get; set; }

    [DataMember]
    public List<int> SomeItems { get; set; }

    public SampleData()
    {
        ContentText = "some text";
        SomeItems = new List<int>() { 1, 2, 3 };
    }
}


Serialization

To serialize an object you need to create an instance of DataContractSerializer class (passing a type of serialized object as an input parameter) and then write serialized data to a stream object using WriteObject method, that accepts stream and object marked with DataContractAttribute attribute as input parameters.

public static void Serialize(Stream streamObject, object objForSerialization)
{
    if (objForSerialization == null || streamObject == null)
        return;

    DataContractSerializer ser = new DataContractSerializer(objForSerialization.GetType());
    ser.WriteObject(streamObject, objForSerialization);
}


Deserialization

Deserialization is also very simple. To deserialize an object you need to create an instance of DataContractSerializer class again (pass constructor a type of serialized object) and then read serialized data out of a stream object using ReadObject method, that accepts stream object as parameter.

public static object Deserialize(Stream streamObject, Type serializedObjectType)
{
    if (serializedObjectType == null || streamObject == null)
        return null;

    DataContractSerializer ser = new DataContractSerializer(serializedObjectType);
    return ser.ReadObject(streamObject);
}


Testing

I have used the following method to test serialization and deserialization using DataContractSerializer. As the result instance of SampleData class after deserialization is exactly the same as the one before the serialization.

public static void Test()
{
    // serialization
    MemoryStream ms = new MemoryStream();
    DataContractSerializationHelper.Serialize(ms, new SampleData());

    ms.Position = 0;
    // deserialization
    var sampleData = DataContractSerializationHelper.Deserialize(ms, typeof(SampleData));

    ms.Close();
}

Here is how serialized instance of SampleData class looks like:

<SampleData xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/EugeneDotnetWPSamples.Serialization.DataContract">
<ContentText>some text</ContentText>
<SomeItems xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:int>1</d2p1:int>
<d2p1:int>2</d2p1:int>
<d2p1:int>3</d2p1:int>
</SomeItems>
</SampleData>



This entry was posted in Development, Serialization, Silverlight, Windows Phone 7 and tagged , , , , . Bookmark the permalink.

One Response to Windows Phone 7 Serialization: DataContract Serialization

  1. Pingback: Windows Phone 7 序列化:DataContract Serialization » Tmango

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comments links could be nofollow free.

Notify me of followup comments via e-mail. You can also subscribe without commenting.