Object serialization is the process of converting an object to a format that is suitable for persistence (database, file, etc) or transportation (remoting, Web Services, MSMQ, etc).

The format of the output byte stream is governed by a formatter object. When you serialize data, you construct a formatter object that implements the required format.

With .NET Framework 2.0 and above you can use two formatters: BinaryFormatter and SoapFormatter. You can also serialize objects (well, just the public members, not the private ones - which is know as shallow serialization) by using the XMLSerializer class.

The following class Person implements some attributes that are used in the process of seralization. This class is also used on the application example you can download below.

 [Serializable] //<-- This atribute is just required by BinaryFormatter and SoapFormatter
    public class Person  //<-- XMLSerializer needs that the class is defined as public
    {
        //[System.Xml.Serialization.XmlIgnore]   //<-- using this attribute, this field will be ignored in Xml Serialization        

        public string FirstName; //Some few public properties to serialize. They  will be serialize by the three formatters.

        public string LastName;                
               
        [NonSerialized] //<-- Using this attribute, the field Nationality won't be serialized (by any of the three serializers)
        public string Nationality;        
        
        private string _Address; //this private field won't be serialized using XmlSerialization. They will be serialized using Binary or Soap formatters

        private string _ZIPCode; //this private field won't be serialized  using XmlSerialization. They will be serialized using Binary or Soap formatters

		//let's create a method to set the private properties.
        public void SetAddress(string address, string zipCode) 
        {
            _Address = address;
            _ZIPCode = zipCode;
        }

        public override string ToString()
        {
            return string.Format("I'm {0} {1} from {2}!. Address: {3}, {4}", 
				FirstName,LastName,Nationality, _Address,_ZIPCode);
        }
    }

Serialization formatters in the .NET Framework

1) BinaryFormatter (System.Runtime.Serialization.Formatters.Binary namespace)

  • Serializes and object in an internal binary format that the .NET Framework understands.
  • The type needs to be marked with the [Serializable] atribute (see class Person)
  • BinaryFormatter saves metadata (assembly and type information) on the output stream along with object data. This information is necessary to deserialize the data and rebuild the object in memory.

PROS

  • The output byte stream generated is compact
  • The serialization process is faster than using the other formatters.
  • This formatter can serialize generic and non generic collections (being the items within the collection serializable)
  • Serializes public and private members (deep serialization)

CONS

  • Format not readable by other techonolgies (just .NET Framework)

BinaryFormatter serialization use example

Person p=new Person();
string path=@"c:\myfile.bin";
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	b.Serialize(fs, p);
	fs.Close();
}

This code will serialize object p (type Person) on file c:\myfile.bin with binary format

BinaryFormatter deserialization use example:

string path=@"c:\myfile.bin";
using (System.IO.FileStream ds = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	Person p = bf.Deserialize(ds) as Person;	
}

This code will deserialize object p (type Person) from c:\myfile.bin

2) SoapFormatter (System.Runtime.Serialization.Formatters.Soap namespace)

  • Serializes an object in SOAP format.
  • The type also needs to be marked with the [Serializable] atribute.
  • To use this class you need a reference to the System.Runtime.Serialization.Soap assembly.
  • This formatter also saves metadata (assembly and type information) on the output stream along with object data.

PROS

  • Follows a standard (SOAP) that other platforms can understand.
  • Serializes public and private members (deep serialization)

CONS

  • It is more verbose (less efficient) than BinaryFormatter.
  • It can NOT serialize generic collections (System.Collections.Generic namespace)

SoapFormatter serialization use example:

Person p=new Person();
string path=@"c:\myfile.soap";
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
	System.Runtime.Serialization.Formatters.Soap.SoapFormatter
	f = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
	f.Serialize(fs, p);
	fs.Close();
}

This code will serialize object p (type Person) on file c:\myfile.soap with Soap format

SoapFormatter deserialization use example:

string path=@"c:\myfile.soap";
using (System.IO.FileStream ds = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
	Person p = sf.Deserialize(ds) as Person;
	AppendToLog(string.Format("Single person deserialized from {0} in SOAP format: {1}", path, p));
}

This code will deserialize object p (type Person) from file on c:\myfile.soap using Soap formatter

A Person object after Soap serialization looks like this:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
	<SOAP-ENV:Body>
		<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Serialization/dotneat_net.Serialization%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
			<FirstName id="ref-3">Joe</FirstName>
			<LastName id="ref-4">Doe</LastName>
			<_Address id="ref-5">dotneat.net Street, Zaragoza, Spain</_Address>
			<_ZIPCode id="ref-6">50007</_ZIPCode>
		</a1:Person>
	</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

3) XMLSerializer

  • Serializes and object in XML format.
  • Requeriments:
    • Type must be public (public class person)
    • Must implement a parameterless constructor (in order to deserialize the object)
    • If you are serializing a non generic collection of items, you must pass the types that are stored in the collection as a parameter in the constructor of the XmlSerializer (see example code).

PROS

  • It can serialize generic and non generic collections (being the items within the collection serializable)
  • Class doesn't need to be decorated with [Serializable] attribute.
  • Developer has a deep control about how each field is going to be serialized by using the attributes:
    • [XmlAttribute] : over a field, marks that the field will be serialized as attribute, instead of a node
    • [XmlIgnore] : won't serialize that field. The same as NonSerializable, but just for the XmlSerializer.
    • [XmlElement (ElementName="NewName"]: Allows you to rename the field when being serialized.
    • ....

CONS

  • Only public members will be serialize! (shallow serialization) (both BinaryFormatter and SoapFormatter would serialize also object private members)

XmlSerializer serialization use example:

Person p=new Person();
string path=@"c:\myfile.xml";
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
using (System.IO.FileStream xmlStream = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
	serializer.Serialize(xmlStream, p);
	xmlStream.Close();
}

This code will serialize object p (type Person) on file on c:\myfile.xml using the XmlSerializer class

XmlSerializer deserialization use example:

string path=@"c:\myfile.xml";
System.Xml.Serialization.XmlSerializer dxml = new System.Xml.Serialization.XmlSerializer(typeof(Person));
using (System.IO.FileStream xmlStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	Person p = dxml.Deserialize(xmlStream) as Person;
	xmlStream.Close();
}                

This code will deserialize object p (type Person) from file c:\myfile.xml using the XmlSerializer class

A Person object after XML serialization looks like this (see how just public members are serialized):

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Joe</FirstName>
  <LastName>Doe</LastName>
</Person>

As you may see, private members are not serialized.

Selecting Fields to serialize

You can omit fields from being serialized by marking them with the [NonSerialized] attribute (see Nationality field in Person class).

Customizing the process of serialization and deserialization

If you are required to, you can modify the way the data in objects is serialized and deserialized. For example, you may want to serialize the account number and pass code of the class BackAccount crypted (just those two fields)

Serialization process

You need to implement the interface ISerializable on the class to serialize. If the type implements ISerializable interface, the formatter calls the GetObjectData to convert the object into the stream of bytes.

Use OnSerializingAttribute and OnSerializedAttribute to mark methods that will be executed before and after the serialization takes place.

[Serializable]
public class Person : ISerializable{

    .....

    [OnSerializing]
    public void Deserializing (StreamingContext context){
        //before serialization
    }


    [OnSerialized]
    public void Serialized (StreamingContext context){
        //after serialization
    }
}

Deserialization process

It is also possible to control how the deserialization process by implementing a constructor that takes a SerializationInfo and a StreamingContext as parameters.

[Serializable]
public class Person : ISerializable{
    //Deserialization constructor
    private Person(SerializationInfo info, StreamingContext context){
        string fname=info.GetString("FirstName");    
        // ...   
    }
}

Use OnDeserializingAttribute and OnDeserializedAttribute to specify methods to run before and after the object is deserialized.

[Serializable]
public class Person : ISerializable{

    .....

    [OnDeserializing]
    public void Deserializing (StreamingContext context){
        //before deserialization
    }


    [OnDeserialized]
    public void Deserialized (StreamingContext context){
        //after deserialization
    }

}

Example application code


(click on the image to view screenshot in full size)

Serialization application example source code (hosted on google code)

About the example application

You can use the application for serialize/deserialize a simple example class "Person". You can go and check file size and format of output file. You can also serialize/deserilize non generic (ArrayList) and generic (List) collections of Person, so you can see how the formatters serialize those types.

Performance

There is a performance test functionality. You can check which is the faster way of serializing a simple type. Feel free to extend the example to create performance tests that suits your needs

Final review

kick it on DotNetKicks.com AddThis Social Bookmark Button

Tuesday, April 07, 2009 1:16:37 PM UTC
Dude, you completely left out the DataContractSerializer and XAML. Okay, so the DCS isn't all that impressive, but its still better than the XmlSerializer. And the XamlReader/Writer? How could you leave those out? We'll all be serializing to xaml within the next two-four years. Its designed for serializing/deserializing objects; XML isn't, and shows it in its many annoying buggy ways.

A couple more points.

You can control Xml serialization via IXmlSerializable, which means you can easily serialize private members. Which would, of course, be foolish; opening your private data up for anybody to modify. If you do that, what's the point of keeping it private anyway? And the XmlSerializer has LOTS of cons. From creating private assemblies to severe limitations (no dictionaries, sorry!). Google the XmlSerializer and read the woes.

And binary serialized objects ARE readable by other technologies! I'm not sure where you're getting that. As long as you know the contents of the binary file, you can open it and parse out the data. For example, you don't have to be running a .net program to know that the first 32 bytes of the file constitute a 32bit integer. The types may not exactly map into the language you may happen to be using, but the information needed to parse the binary file is freely available.
Monday, August 31, 2009 8:10:28 PM UTC
In the SOAP example, is there anyway to control the xmlns on the object? For example in your "person" object, it was:

xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Serialization/dotneat_net.Serialization%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"

I'd like to override this with a different assembly name, to be backwards compatible with some old code.
Wednesday, September 09, 2009 2:39:15 PM UTC
@jorge: Have you tried to do it through custom serialization?
Monday, December 21, 2009 7:30:01 AM UTC
teste
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, em, i, strike, strong) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview

Yeap, the sponsors! :-)

On this page...

Tags

Calendar

<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

Navigation

Archives

Recommended .NET blogs

The author

Iván Loire
Iván Loire (Zaragoza, Spain)

View Ivan Loire's profile on LinkedIn
Microsoft Certified Trainer
Send mail to the author(s) E-mail

Syndication

Feed Icon