Understanding Serialization and Deserialization in C#

A clear guide to converting objects into data formats and back using C#

Posted by Hüseyin Sekmenoğlu on May 22, 2019 Backend Development Programming Fundamentals

๐Ÿ’พ What Is Serialization?

Serialization is the process of converting an object into a data format such as a string or stream so it can be stored in a file or sent over the network. Deserialization is the reverse process which reconstructs the original object from that data.

In C# this is commonly done using libraries like System.Text.Json, System.Runtime.Serialization or System.Xml.Serialization.


๐Ÿงฑ Example: Serializing an Object to JSON

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Create and serialize the object
var product = new Product { Id = 1, Name = "Book" };
string json = JsonSerializer.Serialize(product);
Console.WriteLine(json);

Output:

{"Id":1,"Name":"Book"}

๐Ÿงฑ Example: Deserializing JSON Back to an Object

string json = "{\"Id\":1,\"Name\":\"Book\"}";

// Convert JSON string back to object
Product deserializedProduct = JsonSerializer.Deserialize<Product>(json);
Console.WriteLine(deserializedProduct.Name); // Output: Book

This mechanism is essential for scenarios such as caching, web APIs, file storage and inter-service communication.


๐Ÿ“ฆ Example: Writing to and Reading from a File

// Serialize to file
File.WriteAllText("product.json", json);

// Read from file and deserialize
string fileJson = File.ReadAllText("product.json");
Product productFromFile = JsonSerializer.Deserialize<Product>(fileJson);

These examples show how serialization makes it easy to persist and retrieve objects as plain text. Whether you are building APIs, saving configuration or handling data between systems understanding this process is essential.

โš™๏ธ Types of Serialization in C#

C# offers several serialization techniques each suitable for different use cases. Understanding these methods can help you choose the right one for your application.


๐Ÿ”˜ Binary Serialization

Binary serialization transforms objects into a compact binary format which is efficient in terms of size and performance. It requires the [Serializable] attribute on classes.

Usage:

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

This format is ideal when performance and data size matter. However it is not human-readable and should not be used in scenarios where data portability or inspection is needed.


๐Ÿ“ฆ SOAP Serialization

SOAP serialization converts an object into XML using the Simple Object Access Protocol format. It is primarily used for communication with legacy web services that still rely on SOAP.

While mostly obsolete for modern APIs it may still be required in enterprise environments.


๐ŸŒ JSON Serialization

JSON serialization is the most widely used format today. It converts objects into a JSON string which is lightweight readable and ideal for web APIs.

Example using System.Text.Json:

var json = JsonSerializer.Serialize(myObject);
var obj = JsonSerializer.Deserialize<MyClass>(json);

You can also use libraries like Newtonsoft.Json for more advanced features like custom converters or property filtering.


๐Ÿ“„ XML Serialization

XML Serialization converts objects into XML format. It is supported through the System.Xml.Serialization.XmlSerializer class.

  • Only public properties and fields are serialized

  • Does not require [Serializable] attribute

  • Good for interoperability with systems that expect XML

XmlSerializer serializer = new XmlSerializer(typeof(Product));
serializer.Serialize(stream, product);

๐Ÿ“„ Data Contract Serialization

Available through System.Runtime.Serialization, this method uses [DataContract] and [DataMember] attributes.

  • Offers more control over the serialization process

  • Supports both XML and JSON formats (with DataContractJsonSerializer)

[DataContract]
public class Product
{
    [DataMember]
    public int Id { get; set; }
    
    [DataMember]
    public string Name { get; set; }
}

This is commonly used in WCF (Windows Communication Foundation) applications.


โšก Custom Serialization (ISerializable Interface)

For complete control, you can implement the ISerializable interface. This lets you define exactly how each property is serialized and deserialized.

[Serializable]
public class CustomProduct : ISerializable
{
    public string Name;

    public CustomProduct() {}

    protected CustomProduct(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("CustomName");
    }

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

This is useful for complex or versioned data structures.


๐ŸŒ YAML and Other Formats (via Third-party Libraries)

Using libraries like YamlDotNet or MessagePack for C#, you can serialize to other formats such as:

  • YAML: Human-readable, ideal for configuration files

  • MessagePack: Compact binary format, faster and smaller than JSON

  • Protobuf (Protocol Buffers): Used by gRPC for highly efficient cross-platform serialization


๐Ÿงช Summary Table

Type

Format

Library / Attribute

Use Case

Binary

Binary

[Serializable]

Internal fast serialization

JSON

JSON

System.Text.Json, Newtonsoft

Web APIs, modern apps

SOAP

XML

Legacy APIs

Integration with old services

XML

XML

XmlSerializer

Config files, interoperability

Data Contract

XML or JSON

[DataContract], [DataMember]

WCF, service contracts

Custom (ISerializable)

Any

ISerializable

Full control, version tolerance

YAML / MessagePack

YAML, Binary

Third-party libraries

Config, performance critical systems


โœ… Final Thoughts

Choosing the right serialization approach depends on your specific application needs. JSON is great for web APIs, XML is better for config or legacy and binary or MessagePack is optimal for speed and performance. Always consider readability, speed and compatibility when selecting your serialization strategy.