Serialization is the process of converting an object into a format that can be easily stored (such as in a file or database) or transmitted (over a network). The reverse process, where serialized data is transformed back into an object, is called deserialization.
In .NET, serialization is supported through different techniques, and it plays a critical role in scenarios like saving the state of an object, communication between different components of an application, and working with distributed systems.
Each serialization type is used depending on the format and needs of the application.
Binary Serialization converts an object into a binary format, making it compact and efficient for storage or transmission. This format is not human-readable and is used when performance is a priority, especially in scenarios where the object will only be deserialized within the same application.
[Serializable] attribute.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()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize the object to a file
using (FileStream stream = new FileStream("person.dat", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
Console.WriteLine("Object serialized to person.dat.");
}
// Deserialize the object from the file
using (FileStream stream = new FileStream("person.dat", FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
Person deserializedPerson = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
}
}
}
In this example, the Person object is serialized into a binary file and later deserialized back into an object.
XML Serialization converts an object into an XML format. This format is human-readable, widely used, and can be transmitted easily across different systems or platforms. XML serialization is useful for web services, configuration files, or storing data in a structured, readable format.
[XmlElement] attribute for custom mapping.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()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize the object to XML format
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
using (StreamWriter writer = new StreamWriter("person.xml"))
{
xmlSerializer.Serialize(writer, person);
Console.WriteLine("Object serialized to person.xml.");
}
// Deserialize the object from the XML file
using (StreamReader reader = new StreamReader("person.xml"))
{
Person deserializedPerson = (Person)xmlSerializer.Deserialize(reader);
Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
}
}
}
In this example, the Person object is serialized into an XML file and later deserialized back into an object.
JSON Serialization converts an object into a JSON format, which is lightweight, easy to read, and commonly used in web services, APIs, and web applications. JSON is platform-independent, making it ideal for exchanging data between systems built with different technologies.
Newtonsoft.Json (a popular third-party library) or the built-in System.Text.Json (in .NET Core and later).System.Text.Json)using System;
using System.IO;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize the object to JSON format
string jsonString = JsonSerializer.Serialize(person);
File.WriteAllText("person.json", jsonString);
Console.WriteLine("Object serialized to person.json.");
// Deserialize the object from JSON
string jsonStringFromFile = File.ReadAllText("person.json");
Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonStringFromFile);
Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
}
}
Newtonsoft.Json)using System;
using Newtonsoft.Json;
using System.IO;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize the object to JSON format using Newtonsoft.Json
string jsonString = JsonConvert.SerializeObject(person);
File.WriteAllText("person.json", jsonString);
Console.WriteLine("Object serialized to person.json.");
// Deserialize the object from JSON
string jsonStringFromFile = File.ReadAllText("person.json");
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(jsonStringFromFile);
Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
}
}
Both System.Text.Json and Newtonsoft.Json offer similar functionality for JSON serialization and deserialization, with Newtonsoft.Json providing more features and flexibility, and System.Text.Json being faster and more lightweight.
In some cases, you may need to control how an object is serialized or deserialized, such as excluding certain fields or performing custom processing. This is where Custom Serialization comes into play.
.NET provides mechanisms to implement custom serialization logic using interfaces like ISerializable and attributes like [OnSerializing], [OnDeserialized], etc.
ISerializableusing System;
using System.IO;
using System.Runtime.Serialization;
[Serializable]
public class Person : ISerializable
{
public string Name { get; set; }
public int Age { get; set; }
// Custom serialization constructor
public Person(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
Age = info.GetInt32("Age");
}
// Implement GetObjectData to control how the object is serialized
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
info.AddValue("Age", Age);
}
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize the object to a file with custom serialization
using (FileStream stream = new FileStream("person_custom.dat", FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
Console.WriteLine("Object serialized with custom serialization.");
}
// Deserialize the object from the file
using (FileStream stream = new FileStream("person_custom.dat", FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Person deserializedPerson = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
}
}
}
In this example, the Person class implements ISerializable, providing custom logic for serialization and deserialization through the GetObjectData and the constructor that takes SerializationInfo.
Serialization is useful in scenarios like:
Open this section to load past papers