Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Serialization

Introduction to Serialization

Serialization is the process of converting an object into a format that can be easily transported or stored. In .NET, serialization is commonly used for saving object states, sending objects over the network, and for other purposes.

Types of Serialization

In .NET, there are several types of serialization, including:

  • Binary Serialization
  • XML Serialization
  • JSON Serialization

Binary Serialization

Binary serialization converts an object into a binary format. The System.Runtime.Serialization.Formatters.Binary namespace provides the BinaryFormatter class to perform binary serialization.

Example: Binary Serialization


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

[Serializable]
public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program {
    static void Main(string[] args) {
        Person person = new Person { Name = "John", Age = 30 };
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream("person.bin", FileMode.Create)) {
            formatter.Serialize(stream, person);
        }

        using (FileStream stream = new FileStream("person.bin", FileMode.Open)) {
            Person deserializedPerson = (Person)formatter.Deserialize(stream);
            Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
        }
    }
}
    

XML Serialization

XML serialization converts an object into an XML format. The System.Xml.Serialization namespace provides the XmlSerializer class to perform XML serialization.

Example: XML Serialization


using System;
using System.IO;
using System.Xml.Serialization;

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program {
    static void Main(string[] args) {
        Person person = new Person { Name = "John", Age = 30 };
        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        using (FileStream stream = new FileStream("person.xml", FileMode.Create)) {
            serializer.Serialize(stream, person);
        }

        using (FileStream stream = new FileStream("person.xml", FileMode.Open)) {
            Person deserializedPerson = (Person)serializer.Deserialize(stream);
            Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
        }
    }
}
    

JSON Serialization

JSON serialization converts an object into a JSON format. The System.Text.Json namespace provides the JsonSerializer class to perform JSON serialization.

Example: JSON Serialization


using System;
using System.Text.Json;
using System.IO;

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program {
    static void Main(string[] args) {
        Person person = new Person { Name = "John", Age = 30 };
        string jsonString = JsonSerializer.Serialize(person);
        File.WriteAllText("person.json", jsonString);

        string jsonStringFromFile = File.ReadAllText("person.json");
        Person deserializedPerson = JsonSerializer.Deserialize(jsonStringFromFile);
        Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
    }
}
    

Custom Serialization

In some cases, you might need more control over the serialization process. You can implement the ISerializable interface to customize the serialization process.

Example: Custom Serialization


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

[Serializable]
public class Person : ISerializable {
    public string Name { get; set; }
    public int Age { get; set; }

    public Person() { }

    protected Person(SerializationInfo info, StreamingContext context) {
        Name = info.GetString("Name");
        Age = info.GetInt32("Age");
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context) {
        info.AddValue("Name", Name);
        info.AddValue("Age", Age);
    }
}

class Program {
    static void Main(string[] args) {
        Person person = new Person { Name = "John", Age = 30 };
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream("person_custom.bin", FileMode.Create)) {
            formatter.Serialize(stream, person);
        }

        using (FileStream stream = new FileStream("person_custom.bin", FileMode.Open)) {
            Person deserializedPerson = (Person)formatter.Deserialize(stream);
            Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
        }
    }
}
    

Conclusion

Serialization is a crucial concept in .NET for saving object states, sending objects over networks, and more. Understanding the different types of serialization and how to implement them will help you build robust and scalable applications.