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)

'Declaration
Public NotInheritable Class DataContractSerializer
	Inherits XmlObjectSerializer
'Usage
Dim instance As DataContractSerializer

public final class DataContractSerializer extends XmlObjectSerializer
public final class DataContractSerializer extends XmlObjectSerializer
Not applicable.

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 Windows Communication Foundation (WCF) messages. Apply the DataContractAttribute attribute to classes, and the DataMemberAttribute attribute to class members to specify properties and fields that will be serialized.

For a list of types that can be serialized, see Types Supported by the Data Contract Serializer.

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.

For more information about using the DataContractSerializer, see Using Stand-alone Serialization.

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, regardless of accessibility: private, protected, internal, protected internal, or public.

NoteNote:

The DataContractAttribute attribute should not be applied to classes that already implement the ISerializable interface or that are marked with the SerializableAttribute. An exception is thrown if you try to serialize an instance of such a type.

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.

If you are creating a class that has fields or properties that need to be populated before the serialization or deserialization occurs, use callback attributes, as described in Version Tolerant Serialization Callbacks.

Adding to the Collection of Known Types

When serializing or deserializing an object, it is required that the type is "known" to the DataContractSerializer. Begin by creating an instance of a class that implements IEnumerable (such as List) and adding the known types to the collection. Then create an instance of the DataContractSerializer using one of the overloads that takes the IEnumerable (for example, DataContractSerializer.

Forward Compatibility

The DataContractSerializer understands data contracts that have been designed to be compatible with future versions of the contract. Such types implement the IExtensibleDataObject interface. The interface features the ExtensionData property that returns an ExtensionDataObject object. For more information, see Forward Compatible Data Contracts.

The following example code shows a type named Person that is serialized by the DataContractSerializer. The DataContractAttribute attribute is applied to the class, and the DataMemberAttribute is applied to members to instruct the DataContractSerializer what to serialize.

' You must apply a DataContractAttribute or SerializableAttribute
' to a class to have it serialized by the DataContractSerializer.
<DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
Class Person
    Implements IExtensibleDataObject
    <DataMember()>  _
    Public FirstName As String
    <DataMember()>  _
    Public LastName As String
    <DataMember()>  _
    Public ID As Integer
    
    Public Sub New(ByVal newfName As String, ByVal newLName As String, ByVal newID As Integer) 
        FirstName = newfName
        LastName = newLName
        ID = newID
    End Sub 
    
    Private extensionData_Value As ExtensionDataObject
    
    Public Property ExtensionData() As ExtensionDataObject Implements _
       IExtensibleDataObject.ExtensionData
        Get
            Return extensionData_Value
        End Get
        Set
            extensionData_Value = value
        End Set
    End Property
End Class 


NotInheritable Public Class Test
    
    Private Sub New() 
    
    End Sub 
     
    Public Shared Sub Main() 
        Try
            WriteObject("DataContractSerializerExample.xml")
            ReadObject("DataContractSerializerExample.xml")
        
        Catch serExc As SerializationException
            Console.WriteLine("Serialization Failed")
            Console.WriteLine(serExc.Message)
        Catch exc As Exception
            Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", exc.Message, exc.StackTrace)
        
        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try
    End Sub 
    
    Public Shared Sub WriteObject(ByVal fileName As String) 
        Console.WriteLine("Creating a Person object and serializing it.")
        Dim p1 As New Person("Zighetti", "Barbara", 101)
        Dim writer As New FileStream(fileName, FileMode.Create)
        Dim ser As New DataContractSerializer(GetType(Person))
        ser.WriteObject(writer, p1)
        writer.Close()
    End Sub 

    Public Shared Sub ReadObject(ByVal fileName As String) 
        Console.WriteLine("Deserializing an instance of the object.")
        Dim fs As New FileStream(fileName, FileMode.Open)
        Dim reader As XmlDictionaryReader = _
            XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
        Dim ser As New DataContractSerializer(GetType(Person))
        
        ' Deserialize the data and read it from the instance.
        Dim deserializedPerson As Person = CType(ser.ReadObject(reader, True), Person)
        reader.Close()
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.ID))
    End Sub 
End Class 

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.

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0

Community Additions

ADD
Show: