.NET Framework Class Library
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)
Syntax

Visual Basic (Declaration)
Public NotInheritable Class DataContractSerializer _
    Inherits XmlObjectSerializer
Visual Basic (Usage)
Dim instance As DataContractSerializer
C#
public sealed class DataContractSerializer : XmlObjectSerializer
Visual C++
public ref class DataContractSerializer sealed : public XmlObjectSerializer
JScript
public final class DataContractSerializer extends XmlObjectSerializer
Remarks

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 are 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.

You can set the type of a data contract serializer using the <dataContractSerializer> element in a client application configuration file.

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.

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 must 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<(Of <(T>)>) (such as List<(Of <(T>)>)) and adding the known types to the collection. Then create an instance of the DataContractSerializer using one of the overloads that takes the IEnumerable<(Of <(T>)>) (for example, DataContractSerializer(Type, IEnumerable<(Of <(Type>)>)).

NoteNote:

Unlike other primitive types, the DateTimeOffset structure is not a known type by default, so it must be manually added to the list of known types (see Data Contract Known Types).

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.

Running under Partial Trust

When instantiating the target object during deserialization, the DataContractSerializer does not call the constructor of the target object. If you author a [DataContract] type that is accessible from partial trust (that is, it is public and in an assembly that has the AllowPartiallyTrustedCallers attribute applied) and that performs some security-related actions, you must be aware that the constructor is not called. In particular, the following techniques do not work:

  • If you try to restrict partial trust access by making the constructor internal or private, or by adding a LinkDemand to the constructor -- neither of these have any effect during deserialization under partial trust.

  • If you code the class that assumes the constructor has run, the class may get into an invalid internal state that is exploitable.

Examples

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.

Visual Basic
' 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 
C#
namespace DataContractSerializerExample
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Xml;

    // 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 : IExtensibleDataObject
    {
        [DataMember()]
        public string FirstName;
        [DataMember]
        public string LastName;
        [DataMember()]
        public int ID;

        public Person(string newfName, string newLName, int newID)
        {
            FirstName = newfName;
            LastName = newLName;
            ID = newID;
        }

        private ExtensionDataObject extensionData_Value;

        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionData_Value;
            }
            set
            {
                extensionData_Value = value;
            }
        }
    }

    public sealed class Test
    {
        private Test() { }

        public static void Main()
        {
            try
            {
                WriteObject("DataContractSerializerExample.xml");
                ReadObject("DataContractSerializerExample.xml");

            }

            catch (SerializationException serExc)
            {
                Console.WriteLine("Serialization Failed");
                Console.WriteLine(serExc.Message);
            }
            catch (Exception exc)
            {
                Console.WriteLine(
                "The serialization operation failed: {0} StackTrace: {1}",
                exc.Message, exc.StackTrace);
            }

            finally
            {
                Console.WriteLine("Press <Enter> to exit....");
                Console.ReadLine();
            }
        }

        public static void WriteObject(string fileName)
        {
            Console.WriteLine(
                "Creating a Person object and serializing it.");
            Person p1 = new Person("Zighetti", "Barbara", 101);
            FileStream writer = new FileStream(fileName, FileMode.Create);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            ser.WriteObject(writer, p1);
            writer.Close();
        }

        public static void ReadObject(string fileName)
        {
            Console.WriteLine("Deserializing an instance of the object.");
            FileStream fs = new FileStream(fileName,
            FileMode.Open);
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(Person));

            // Deserialize the data and read it from the instance.
            Person deserializedPerson =
                (Person)ser.ReadObject(reader, true);
            reader.Close();
            fs.Close();
            Console.WriteLine(String.Format("{0} {1}, ID: {2}",
            deserializedPerson.FirstName, deserializedPerson.LastName,
            deserializedPerson.ID));
        }
    }
Inheritance Hierarchy

System..::.Object
  System.Runtime.Serialization..::.XmlObjectSerializer
    System.Runtime.Serialization..::.DataContractSerializer
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0
See Also

Reference

Other Resources

Tags :


Community Content

ChrisLaMont
Alternate Sample Using Memory Stream

Just some sample code that uses an in-memory stream instead of System.IO.File. One thing to note is that DataContractSerializer saves as UTF8, not Unicode Encoding as some other XMLReader samples demonstrate.

If you see a way to alter the format ot the XML (compressed, or indented), please update this comment (or send me an email). Thanks!

namespace

serialTest

{

[

DataContract]

classmyTest

{

[

DataMember]

string First;

[

DataMember]

publicstring Last;

[

DataMember]

publicint age;

}

classProgram

{

staticvoid Main(string[] args)

{

myTest m = newmyTest { age = 59, Last = "Mankowski" };

System.IO.

MemoryStream someStream = new System.IO.MemoryStream();

DataContractSerializer dcs = newDataContractSerializer(typeof( myTest));

dcs.WriteObject(someStream, m);

someStream.Seek(0, System.IO.

SeekOrigin.Begin);

XmlDictionaryReader reader =

XmlDictionaryReader.CreateTextReader(someStream, newXmlDictionaryReaderQuotas());

// Read the remaining bytes, byte by byte.

someStream.Seek(0, System.IO.

SeekOrigin.Begin);

byte[] byteArray = newbyte[someStream.Length];

int count = someStream.Read(byteArray, 0, 20);

while (count < someStream.Length)

{

byteArray[count++] =

Convert.ToByte(someStream.ReadByte());

}

// Decode the byte array into a char array

// and write it to the console.

UTF8Encoding u8 = newUTF8Encoding();

char[] charArray = newchar[u8.GetCharCount( byteArray, 0, count)];

u8.GetDecoder().GetChars( byteArray, 0, count, charArray, 0);

Console.WriteLine(charArray);

Console.ReadLine();

}

}

}


Funka!
How to format the output XML
As a follow-up to ChrisLaMont's comment, you can format the resultant XML generated by the DataContractSerializer with some help from XmlWriter and XmlWriterSettings.

Example:

var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(myXmlStreamOrFileName, settings))
{
myDataContractSerializer.WriteObject(xmlWriter, myObjectToSerialize);
}

References, including additional samples:
  • XmlWriterSettings Class:
    http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx
  • How to: Specify the Output Format on the XmlWriter:
    http://msdn.microsoft.com/en-us/library/kbef2xz3.aspx


Swaringen Steve
Where is DataContractSerializer?
I know I'm missing something simple, but I can't get Visual Studio 2008 to recognize the existence of the DataContractSerializer class. I'm targeting .Net 3.5. I've included "Using System.Runtime.Serialization" in my C# file. I've included System.Runtime.Serialization.dll as a reference to my project. Still, neither Intellisense nor the compliler recognize the existence of the class. It is documented in my VS2008 help file...but not recognized by the IDE.

Any idea what I'm missing?

Jean-Pierre Fouche
Another Sample - Deserialise and Serialise Generic Object
//Requires AdventureWorks
//Set up your Customer (Sales) dbml before running this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;

namespace SerializeLinq
{
class Program
{
static void Main(string[] args)
{
Serialiser serialiser = new Serialiser();
List<Customer> customers = serialiser.GetCustomers();
string xml = serialiser.GetXML(customers);
Console.WriteLine(xml);

customers = null;
customers = serialiser.GetTypedObject<List<Customer>>(xml);

foreach (Customer customer in customers)
{
Console.WriteLine(customer.CustomerID);
}

Console.ReadKey();
}
}

class Serialiser
{
private static AdventureWorksDataContext db = new AdventureWorksDataContext();
public string GetXML<T>(T objectToSerialise)
{
MemoryStream memoryStream = new MemoryStream();
DataContractSerializer dataContractSerialiser = new DataContractSerializer(typeof(T));
dataContractSerialiser.WriteObject(memoryStream, objectToSerialise);
memoryStream.Seek(0, SeekOrigin.Begin);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());

// Read the remaining bytes, byte by byte.
memoryStream.Seek(0, SeekOrigin.Begin);
byte[] byteArray = new byte[memoryStream.Length];
int count = memoryStream.Read(byteArray, 0, 20);
while (count < memoryStream.Length)
{
byteArray[count++] = Convert.ToByte(memoryStream.ReadByte());
}

// Decode the byte array into a char array
UTF8Encoding utf8Encoding = new UTF8Encoding();
char[] charArray = new char[utf8Encoding.GetCharCount(byteArray, 0, count)];
utf8Encoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
string result = new string(charArray);
return result;
}

public T GetTypedObject<T>(string xml)
{
DataContractSerializer dataContractSerialiser = new DataContractSerializer(typeof(T));
byte[] buffer = GetBuffer(xml);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(buffer, XmlDictionaryReaderQuotas.Max) ;
T typedObject = (T)dataContractSerialiser.ReadObject(reader, true);
return typedObject;
}

public static byte[] GetBuffer(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

public List<Customer> GetCustomers()
{
var q = from c in db.Customers
select c;
List<Customer> customers = q.ToList();
return customers;
}
}
}


Page view tracker