Data Serialization & Deserialization in C#



Data serialization and deserialization in C#, or in any programming language for that matter, are the methods of handling and converting JSON, XML, or binary data into different formats.

What is Serialization?

Data serialization in C# is the process of converting an object into a format that can be easily stored or transmitted into JSON, XML, or binary.

It allows you to save object data to files, send it over a network, or store it in a database.

For example: Converting a C# object into JSON string or XML document.

What is Deserialization?

Deserialization in C# is the reverse process of serialization. It converts stored or transmitted data (JSON/XML) back into a C# object, and enable applications to easily read, process, and reuse structured data.

For example: Converting a JSON or XML string back into a C# class object.

Why Serialization & Deserialization are Important

Both serialisation and deserialisation are important for the following reasons −

  • Enable data transfer between applications or systems.
  • Support persistent storage (saving and loading data).
  • Allow communication with APIs using standard formats like JSON and XML.
  • Simplify configuration management and state saving in applications.

Example: Data Serialization & Deserialisation in C#

In the following example, we develop a C# application that serializes and deserializes data stored in JSON and XML formats.

Folder Structure

Let's see the following folder structure of the "JsonXmlSerializationApp" −

data_serialization_and_deserialization

File: "Company.cs" is a model where you will define the classes that establish the structure of the data your program handles.

namespace JsonXmlSerializationApp.Models {
   public class Company {
      public string Name { get; set; }
      public string Location { get; set; }
      public string Headquarter { get; set; }
   }
}

File − "JsonService.cs" In this file, you will be serializing and deserializing JSON data.

using System;
using System.IO;
using System.Text.Json;
using JsonXmlSerializationApp.Models;

namespace JsonXmlSerializationApp.Services {
   public static class JsonService {
      private static readonly string filePath = "company.json";

      // Serialize Company object to JSON file
      public static void SerializeToJson(Company company) {
         string jsonData = JsonSerializer.Serialize(company, new JsonSerializerOptions { WriteIndented = true });
         File.WriteAllText(filePath, jsonData);
         Console.WriteLine("JSON Serialization complete. Data saved to company.json");
      }

      // Deserialize JSON file to Company object
      public static void DeserializeFromJson() {
         if (File.Exists(filePath)) {
            string jsonData = File.ReadAllText(filePath);
            Company company = JsonSerializer.Deserialize<Company>(jsonData);
            Console.WriteLine("JSON Deserialization complete:");
            Console.WriteLine($"Name: {company.Name}, Location: {company.Location}, Headquarter: {company.Headquarter}");
         }
         else {
            Console.WriteLine("JSON file not found!");
         }
      }
   }
}

File − "XmlService.cs" In this file, you will be serializing and deserializing XML data.

using System;
using System.IO;
using System.Xml.Serialization;
using JsonXmlSerializationApp.Models;

namespace JsonXmlSerializationApp.Services {
   public static class XmlService {
      private static readonly string filePath = "company.xml";

      // Serialize Company object to XML file
      public static void SerializeToXml(Company company) {
         XmlSerializer serializer = new XmlSerializer(typeof(Company));
         using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
            serializer.Serialize(fs, company);
         }
         Console.WriteLine("XML Serialization complete. Data saved to company.xml");
      }

      // Deserialize XML file to Company object
      public static void DeserializeFromXml() {
         if (File.Exists(filePath)) {
            XmlSerializer serializer = new XmlSerializer(typeof(Company));
            using (FileStream fs = new FileStream(filePath, FileMode.Open)){
               Company company = (Company)serializer.Deserialize(fs);
               Console.WriteLine("XML Deserialization complete:");
               Console.WriteLine($"Name: {company.Name}, Location: {company.Location}, Headquarter: {company.Headquarter}");
            }
         }
         else {
            Console.WriteLine("XML file not found!");
         }
      }
   }
}

File − "Program.cs" is the main entry point of a .NET application where program execution start.

using System;
using JsonXmlSerializationApp.Models;
using JsonXmlSerializationApp.Services;

namespace JsonXmlSerializationApp {
   class Program {
      static void Main(string[] args) {
         // Create a Company object
         Company company = new Company {
            Name = "TutorialsPoint",
            Location = "Madhapur, Hyderabad",
            Headquarter = "Hyderabad, India"
         };

         Console.WriteLine("=== JSON Handling ===");
         JsonService.SerializeToJson(company);
         JsonService.DeserializeFromJson();

         Console.WriteLine("\n=== XML Handling ===");
         XmlService.SerializeToXml(company);
         XmlService.DeserializeFromXml();
      }
   }
}

Output − use this command "dotnet run" to run the application.

=== JSON Handling ===
JSON Serialization complete. Data saved to company.json
JSON Deserialization complete:
Name: TutorialsPoint, Location: Madhapur, Hyderabad, Headquarter: Hyderabad, India

=== XML Handling ===
XML Serialization complete. Data saved to company.xml
XML Deserialization complete:
Name: TutorialsPoint, Location: Madhapur, Hyderabad, Headquarter: Hyderabad, India

Conclusion

Serialization and deserialization of data in C# are very important for storing, exchanging, and moving data quickly. With built-in libraries like "System.Text.Json" and "System.Xml.Serialization", developers can quickly transform data into JSON or XML formats and then bring them back when they need to. This approach simplifies data handling in real-world ".NET" projects.

Advertisements