Serialization and Deserialization in C#

03 maart 2021 om 10:00 by ParTech Media - Post a comment

Serialization and deserialization are two of the most common topics discussed in C#. At the same time, it is also one of the most misunderstood terms. Most people are still hazy on its exact purpose in a code.

For example, how many of you know that serialization enables a developer to send an object to a remote application by using a web service? Also, developers use serialization to save the state of an object and re-create it when needed. It provides efficient storage of objects as well as data transfers.

In this post, we are going to dive deep and understand what is serialization and deserialization in C# along with a practical application of it.

Table of Contents

  1. What is serialization and deserialization in C#?
  2. Types of serialization
  3. Practical application of serialization and deserialization in C#
  4. Conclusion

What is serialization and deserialization in C#?

The process of converting an object-type data into a stream of bytes to store the object or transfer it to memory or a database or a file is called serialization. The purpose of this process is to save the state of an object in order to recreate it when needed. It is also used to export application data into a file. The reversal of this process is called deserialization.

Serializing can be used effectively to directly write the data properties of any particular class to a file. Deserialization is used to read the data from the file and construct that class object again.

Types of Serialization

JSON serialization

JavaScript Object Notation (JSON) can be serialized and deserialized with The System.Text.Json namespace. JSON is a lightweight file format for storing and transporting data. JSON serialization serializes the publicly accessible properties of an object into a string, data array of bytes, or stream that abides by the RFC 8259 JSON specification. To manage the way JsonSerializer serializes or deserializes an instance of the class:

  • Use a JsonSerializerOptions object. Learn more about the constructors, properties, and methods here.
  • Pick and use attributes from the System.Text.Json.Serialization namespace to classes or properties
  • Implement custom converters for JSON serialization(called marshalling)

Binary and XML serialization

The System.Runtime.Serialization namespace holds classes for binary and XML serialization and deserialization. Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network data flows. In binary serialization, all members (even all the read-only members), are serialized, and this increases performance. Binary serialization can be prone to undesired results.

XML serialization serializes the public fields/properties/parameters and in turn, returns the values of methods through an XML stream. This XML stream follows a specific XML Schema definition language (XSD) document. XML serialization leads to strongly typed classes that possess public properties and fields, which in turn are converted to XML. System.Xml.Serialization contains classes for serializing and deserializing the XML classes. You apply attributes to classes and class members to control the way the XmlSerializer serializes or deserializes an instance of the class, that is, the object.

Designer serialization

Designer serialization is another type(special type) of serialization that has a type of object persistence associated with development tools. It is a process where you convert an object graph into a source code file. This can then be used to reconstruct the object graph. A source file can contain code, markup, or SQL table information. Here you can have a better idea about System.ComponentModel.Design.Serialization Namespace

Practical Application of serialization and deserialization in C#

Here we have taken an example of Tutorial class and Tutorial object to demonstrate the concept of serialization and deserialization.

Main Steps

  1. Create a class called Tutorial which has 2 properties - ID and Name
  2. Now create an object from the class and assign the numerical value - "1" to the ID property and a value of ".Net" to the name property.
  3. Now use serialization to serialize the above object to a file called Example.txt
  4. Finally, use deserialization to deserialize the object from the file. Display the output values in the console.

Step 1

Adding the class which will be used for serialization

  • The class which needs to be serialized must have the [Serializable] attribute. This is a dedicated keyword in C#. Add this keyword to the Tutorial class. If you don't add this attribute, you will receive an error whenever you serialize the class.
  • Now we need to define the class which will be serialized. Here we are defining a class called "Tutorial" and providing 2 properties, one is "ID" and another one is "Name."

Step 2

Here we will initialize the object of the Tutorial class, and then create the file stream as shown. It will then serialize to the file named “Example.txt”

  • Let us begin by creating an object of the Tutorial class. Now assign the numerical value - "1" to ID and ".Net" to the name property.
  • Now use the formatter class to serialize or convert the object to a binary format. The data in the file in serialization is created in binary format. Next, we will create a file stream object. The file stream object is used to open the file Example.txt that is just created for writing purposes. The keywords FileMode.Create and FileMode.Write is used to specify that the file should be opened for writing purposes.
  • Finally, we use the Serialize() method to transfer the required binary data(the created object) to the file. After that, we then close the stream, since the write operation is complete.

Step 3

Finally, to check if the correct data is present in the file, we use the Deserialize() function to deserialize the object from the created file.

The Code

using System;

using System.IO;

using System.Linq;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using System.Text;

using System.Threading.Tasks;

namespace DemoApplication

{

 [Serializable]

 class Tutorial

 {

 public int ID;

 public String Name;

  static void Main(string[] args)

  {

  Tutorial obj = new Tutorial();

  obj.ID = 1;

  obj.Name = ".Net";



  IFormatter formatter = new BinaryFormatter();

  Stream stream = new   FileStream(@"E:\ExampleNew.txt",FileMode.Create,FileAccess.Write);



  formatter.Serialize(stream, obj);

  stream.Close();



  stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Open,FileAccess.Read);

  Tutorial objnew = (Tutorial)formatter.Deserialize(stream);



  Console.WriteLine(objnew.ID);

  Console.WriteLine(objnew.Name);



  Console.ReadKey();

 }

 }

}


  • We create the object "stream" of our required class to open the file Example.txt in read-only mode.
  • After that, we use formatter class to deserialize the object. This is stored in the Example.txt file. The returned object is set to objnew(object).
  • Finally, we display the properties "objnew" to the console. This is done using the "ID" and "name" properties.

After writing the above code, the project is run using Visual Studio, you will get the below output.

Visual Studio Code:

Output:

The values of the file are properly deserialized and displayed on the output screen.

Conclusion

Serialization and deserialization have several benefits. You can pass an object through different domains. You can also maintain security or user-centric information across different applications using it.

Nieuwste