Serialization and Deserialization in C# with Examples

Serialization in CSharp
Serialization in C#

What is Serialisation and Deserialization in C#?

Serialization in C# is a process of converting an object into a sequence of bytes. It means putting an object into a form that can be transported across the network and stored in a file, database, or memory. You can use serialization to save an object’s state and reconstruct it when needed. The reverse process of serialization is called deserialization.

The terms “serialization and deserialization” are used when data needs to be transferred between applications.

C# SerializableAttribute Class

If you want to serialize an object such as a class, you should apply the Serializable attribute to it. In case you do not want certain fields in your class to be serialized, you should apply the NonSerialized attribute to those fields.
In most cases, when we serialize an object into a stream, the data is carried along with metadata about that specific object type. This includes its version, assembly name, etc.
Attempting to serialize a type that does not have the Serializable attribute may throw an exception.

Types of Serialization

  • Binary Serialization
  • XML Serialization
  • JSON Serialization
  • SOAP Serialization

Example:

The following is a simple example of serializing a class in C#.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
class Employee
{
    private int id;
    private string name;
    [NonSerialized()]
    private string address;

    public Employee(int rollno, string name, string address)
    {
        this.id = rollno;
        this.name = name;
        this.address = address;
    }
}
public class SerializationExample
{
    public static void Main(string[] args)
    {
       // Initialize an object
        Employee empObject = new Employee(101, "Shekh Ali","Delhi");
        // Create the file stream
        FileStream stream = new FileStream("C:\\MyData\\SerializationExample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, empObject);
        stream.Close();
    }
}

Code Explanation:

  • First, create an object of the Employee class. Then assign the ID the value ‘101’, the name ‘Shekh Ali’, and the value “Delhi” to the address property.
  • Next, create a file stream object to open/create the “SerializationExample.txt” file for writing purposes. Then use the Formatter class that is used to serialize or convert the object to binary format.
  • Finally, use the Serialize method to transfer the binary data to the file. Close the stream once you’ve finished writing.
  • Here, we are serializing the Employee class by adding the Serializable attribute, except for the address field marked with the NonSerialized attribute.

C# Deserialization

In C# programming, deserialization is the process opposite of serialization. It is the process of reading or restoring the serialized data to the object to load it into the memory. This process allows us to reconstruct an object from the bytes of the stream whenever required.

Serialization and Deserialization in CSharp
Deserialization in C#

Example:

Here, In the following example, we are going to use BinaryFormatter.Deserialize(stream) method to deserialize the stream from “SerializationExample.txt” file.

 // Create an object of the BinaryFormatter class.
BinaryFormatter formatter = new BinaryFormatter();
// Create a file stream object
FileStream stream = new FileStream("C:\\MyData\\SerializationExample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);    
Employee employee = (Employee)formatter.Deserialize(stream);
Console.WriteLine($"Id: {employee.id} Name: {employee.name}");      
stream.Close();
Console.ReadLine();

After running the project, you will get the result displayed below.

Deserialization in C# output

Code explanation for deserializing the object:

  • First, create a stream object to read the serialized output.
  • Then create an object of BinaryFormatter class.
  • Finally, call the BinaryFormatter.Deserialize(stream) method to deserialize the stream from a file, and cast it to the specific type.

Serializing Object to XML in C#

The .NET Framework includes powerful objects that can serialize any object to XML format. The  System.Xml.Serialization  namespace provides the capability to convert the public fields and properties of an object into an XML stream.

using System;
using System.IO;
using System.Xml.Serialization;
public class Employee
{
    public int id;
    public string name;
    public string address;  
}
public class XMLSerializationExample
{
    public static void Main(string[] args)
    {
        // Create an object of the employee class.
        Employee employee = new Employee();
        employee.id = 101;
        employee.name = "Shekh Ali";
        employee.address = "Delhi";

        // Create an instance of the XmlSerializer to accepts the object type as the parameter.
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Employee));

        using (TextWriter txtWriter = new StreamWriter(@"C:\MyData\XMLSerializationExample.xml"))
        {
            xmlSerializer.Serialize(txtWriter, employee);
        }

        //Opening file to read XML data
        FileStream fileStream = new FileStream(@"C:\MyData\XMLSerializationExample.xml",
        FileMode.Open);
        XmlSerializer serializer = new XmlSerializer(typeof(Employee));
        //Calling Deserialize() to deserialize data from the file
        Employee emp = (Employee)serializer.Deserialize(fileStream);
        Console.WriteLine($"Id: {emp.id} Name: {emp.name} Address: {emp.address}");

    }
}

When we will run the above program, the XML file will generate in the specified location.

XMLSerialization in csharp
XMLSerialization in C#

Deserialize an XML file in c#:

The XmlSerializer.Deserialize(Stream) method is used to deserialize the XML document contained by the specified Stream.

deserialize an XML file in csharp
Image: Deserialize an xml file.

JSON Serialization in C#

JSON (JavaScript Object Notation) is one kind of lightweight data format that is designed for running JavaScript on websites. JSON is now widely used on the web for storing and transporting data.
In C#, the System.Text.Json namespace is used to serialize and deserialize from JSON.

The following is a console application program created in Visual Studio to demonstrate the JSON serialization.

using System;
using System.IO;
using System.Text.Json;
public class Employee
{
    public int id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
}
public class JSONSerializationExample
{
    public static void Main(string[] args)
    {
        // Create an object of the employee class.
        Employee employee = new()
        {
            id = 101,
            name = "Shekh Ali",
            address = "Delhi"
        };

        string fileName = @"C:\MyData\Employee.json";
        string jsonString = JsonSerializer.Serialize(employee);
        File.WriteAllText(fileName, jsonString);

        Console.WriteLine(File.ReadAllText(fileName));
        Console.ReadLine();

        // Output: {"id":101,"name":"Shekh Ali","address":"Delhi"}

    }
}

FAQs

Q: What is serialization in C#?

Ans: Serialization is the process of converting the state of an object into a form that can be persisted or carried across the network and saved in a file, database, or memory. The reverse process of serialization is deserialization, which converts a stream into an object.

Q: How many different serialization types are there in C#?

Ans: The three main serialization types offered by C# .NET are binary, soap, and XML serialization.

Q: What are the advantages of serialization?

1. It can be used to send an object from one application to another.
2. To pass an object from one domain to another.
3. To pass an object through a firewall as a JSON or XML string.
4. To Maintain security or user-specific information across applications.

Q: What types of data are acceptable in JSON?

Ans: String, Array, Null, Object, Number, Boolean.

Q: What is the difference between soap and XML serialization in C#?

Ans: XML serialization can be used to serialize an object into an XML stream that conforms to the SOAP specification. SOAP is an XML-based protocol developed specifically for transporting procedure calls using XML. You can use the XmlSerializer class to serialize or deserialize objects.
SOAP serialization uses classes from the System.Runtime.Serialization namespace, and XML serialization use classes from the System.Xml.Serialization namespace.

Q: How to Serialize an Object in C#?

The general steps for serializing an object are:
1. Create an instance of a File that will store a serialized object.
2. Create a stream from the file object.
3. Create an instance of BinaryFormatter class.
4. Call the serialize method of the instance and pass it a stream and object to serialize.

I hope you found this article on “serialization and deserialization in c#” to be interesting. If you find something incorrect or wish to offer more information regarding the subjects discussed here, please leave a comment below.

References: MSDN- Serialization (C#), JavaTpoint- C#-Serialization

Articles to Check Out:

Leave a Comment