Click to Rate and Give Feedback

  Switch on low bandwidth view
This page is specific to
Microsoft Silverlight 3

Other versions are also available for the following:
.NET Framework Class Library for Silverlight
DataContractSerializer Class

Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited.

Namespace:  System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)
Visual Basic (Declaration)
Public NotInheritable Class DataContractSerializer _
    Inherits XmlObjectSerializer
Visual Basic (Usage)
Dim instance As DataContractSerializer
C#
public sealed class DataContractSerializer : XmlObjectSerializer

Use the DataContractSerializer class to serialize and deserialize instances of a type into an XML stream or document. For example, you can create a type named Person with properties that contain essential data, such as a name and address. You can then create and manipulate an instance of the Person class and write all of its property values in an XML document for later retrieval, or in an XML stream for immediate transport. Most important, the DataContractSerializer is used to serialize and deserialize data sent in Silverlight version 3 messages. Apply the DataContractAttribute attribute to classes, and the DataMemberAttribute attribute to class members to specify properties and fields that are serialized.

To use the DataContractSerializer, first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the XmlDictionaryWriter. Then call the WriteObject method to persist the data. To retrieve data, create an object appropriate to reading the data format (such as an XmlDictionaryReader for an XML document) and call the ReadObject method.

Preparing Classes for Serialization or Deserialization

The DataContractSerializer is used in combination with the DataContractAttribute and DataMemberAttribute classes. To prepare a class for serialization, apply the DataContractAttribute to the class. For each member of the class that returns data that you want to serialize, apply the DataMemberAttribute. You can serialize fields and properties, provided they are publicly accessible.

For example, your schema specifies a Customer with an ID property, but you already have an existing application that uses a type named Person with a Name property. To create a type that conforms to the contract, first apply the DataContractAttribute to the class. Then apply the DataMemberAttribute to every field or property that you want to serialize.

NoteNote:

You can apply the DataMemberAttribute to both private and public members.

The final format of the XML need not be text. Instead, the DataContractSerializer writes the data as an XML infoset, which allows you to write the data to any format recognized by the XmlReader and XmlWriter. It is recommended that you use the XmlDictionaryReader and XmlDictionaryWriter classes to read and write, because both are optimized to work with the DataContractSerializer.

Visual Basic
Namespace SL_DataContractSerializer
    Partial Public Class Page
        Inherits UserControl
        Public Sub New()
            InitializeComponent()
        End Sub

        'This uses an event handler, not Silverlight data binding
        Private Sub OnClick(ByVal sender As Object, ByVal args As EventArgs)
            txtOutput1.Text = "Create a User object and serialize it."
            Dim serializedUser As String = WriteFromObject()
            txtOutput2.Text = serializedUser

        End Sub


        ' Create a User object and serializing it.
        Public Shared Function WriteFromObject() As String
            'Create User object.
            Dim user As New User("Bob", 42)

            'Create a stream to serialize the object to.
            Dim ms As New MemoryStream()

            ' Serializer the User object to the stream.
            Dim ser As New DataContractSerializer(GetType(User))
            ser.WriteObject(ms, user)
            Dim array() As Byte = ms.ToArray()
            ms.Close()
            Return Encoding.UTF8.GetString(array, 0, array.Length)
        End Function

    End Class

    <DataContract> _
    Public Class User
        Private privateName As String
        <DataMember> _
        Public Property Name() As String
            Get
                Return privateName
            End Get
            Set(ByVal value As String)
                privateName = value
            End Set
        End Property
        Private privateAge As Integer
        <DataMember> _
        Public Property Age() As Integer
            Get
                Return privateAge
            End Get
            Set(ByVal value As Integer)
                privateAge = value
            End Set
        End Property

        Public Sub New()
        End Sub

        Public Sub New(ByVal newName As String, ByVal newAge As Integer)
            Name = newName
            Age = newAge
        End Sub


    End Class


End Namespace


C#
namespace SL_DataContractSerializer
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        //This uses an event handler, not Silverlight data binding
        void OnClick(object sender, EventArgs args)
        {
            txtOutput1.Text = "Create a User object and serialize it.";
            string serializedUser = WriteFromObject();
            txtOutput2.Text = serializedUser;

        }


        // Create a User object and serializing it.
        public static string WriteFromObject()
        {
            //Create User object.
            User user = new User("Bob", 42);

            //Create a stream to serialize the object to.
            MemoryStream ms = new MemoryStream();

            // Serializer the User object to the stream.
            DataContractSerializer ser = new DataContractSerializer(typeof(User));
            ser.WriteObject(ms, user);
            byte[] array = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(array, 0, array.Length);
        }

    }

    [DataContract]
    public class User
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Age { get; set; }

        public User() { }

        public User(string newName, int newAge)
        {
            Name = newName;
            Age = newAge;
        }


    }


}


System..::.Object
  System.Runtime.Serialization..::.XmlObjectSerializer
    System.Runtime.Serialization..::.DataContractSerializer
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker