Serialize and deserialize objects in C#


[serialize]

Serialization is the process of converting an object into a serial stream-like format. Often that means converting it into XML data for storage or transmission over a network.

Deserialization is the process of using a serialization to rebuild the original object.

Basic serialization in C# is relatively simple. First create the class that you want to serialize and decorate it with the Serializable attribute. Define the class’s properties as usual. Note that the class must be public and must have a default, empty constructor that takes no parameters. Without those two features, the serializer cannot create objects.

The following code shows this example’s Person class.

using System.Xml.Serialization;
...
// The class must be Serializable and public.
[Serializable()]
public class Person
{
    public string FirstName;
    public string LastName;
    public string Street;
    public string City;
    public string State;
    public string Zip;

    // Empty constructor required for serialization.
    public Person()
    {
    }

    // Initializing constructor.
    public Person(string first_name, string last_name,
        string street, string city, string state, string zip)
    {
        FirstName = first_name;
        LastName = last_name;
        Street = street;
        City = city;
        State = state;
        Zip = zip;
    }
}

The following code shows how the program serializes a Person object.

// Create a Person, serialize it, and display the serialization.
private void btnSerialize_Click(object sender, EventArgs e)
{
    // Make a new Person.
    Person per = new Person(
        txtFirstName.Text,
        txtLastName.Text,
        txtStreet.Text,
        txtCity.Text,
        txtState.Text,
        txtZip.Text);

    // Make the XmlSerializer and StringWriter.
    XmlSerializer xml_serializer =
        new XmlSerializer(typeof(Person));
    using (StringWriter string_writer = new StringWriter())
    {
        // Serialize.
        xml_serializer.Serialize(string_writer, per);

        // Display the serialization.
        txtSerialization.Text = string_writer.ToString();
    }

    // Reset the TextBoxes.
    txtFirstName.Clear();
    txtLastName.Clear();
    txtStreet.Clear();
    txtCity.Clear();
    txtState.Clear();
    txtZip.Clear();
}

The code first creates a new Person object, passing its constructor the values entered in the program’s text boxes. It then creates an XmlSerializer object, passing its constructor the type of the object that it will serialize: Person.

Next the code makes a StringWriter object so it can serialize into a string. You could serialize into other stream objects such as file streams if you want.

The code calls the serializer’s Serialize method, passing it the stream in which to serialize (the StringWriter) and the Person object to serialize. The program displays the serialization in the txtSerialization text box.

The following text shows the resulting serialization. Notice that the serializer automatically uses the names of the Person object’s public variables as tags in the resulting XML.

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Mickey</FirstName>
  <LastName>Moose</LastName>
  <Street>1337 Leet St</Street>
  <City>Bugsville</City>
  <State>CA</State>
  <Zip>12345</Zip>
</Person>

The following code shows how the program deserializes the serialization to recreate the Person object.

// Deserialize a Person.
private void btnDeserialize_Click(object sender, EventArgs e)
{
    // Deserialize the serialization.
    XmlSerializer xml_serializer =
        new XmlSerializer(typeof(Person));
    using (StringReader string_reader =
        new StringReader(txtSerialization.Text))
    {
        Person per =
            (Person)(xml_serializer.Deserialize(string_reader));

        // Display the Person's properties in the TextBoxes.
        txtFirstName.Text = per.FirstName;
        txtLastName.Text = per.LastName;
        txtStreet.Text = per.Street;
        txtCity.Text = per.City;
        txtState.Text = per.Street;
        txtZip.Text = per.Zip;
    }

    txtSerialization.Clear();
}

The code creates a new XmlSerializer for Person objects as before. It makes a StringReader initialized to hold the previously created serialization.

Next the code calls the serializer’s Deserialize method, passing it the stream (StringReader) from which it should read the serialization. The Deserialize method returns a generic object so the code casts the result into the Person data type. It then displays the Person object’s field values in the text boxes.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, serialization and tagged , , , , , , , , . Bookmark the permalink.

One Response to Serialize and deserialize objects in C#

  1. Pingback: Control serialization and deserialization in C# - C# HelperC# Helper

Leave a Reply

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