What is Serialization and Deserialization?
Serialization is the process of converting an object into a format that can be easily stored or transmitted, such as JSON, XML, or binary. This is useful for saving the state of an object to a file, sending it over a network, or storing it in a database.
Deserialization is the reverse process, where the serialized data is converted back into an object. This allows you to reconstruct the object from its serialized form.
Why Use Serialization and Deserialization?
Persistence: Save the state of an object to a file or database for later use.
Communication: Send objects over a network (e.g., in web APIs, microservices).
Caching: Store objects in memory or on disk for quick retrieval.
Interoperability: Exchange data between different systems or languages using standard formats like JSON or XML.
How to Serialize and Deserialize in C#
C# provides several ways to serialize and deserialize objects, including:
JSON Serialization (using System.Text.Json
or Newtonsoft.Json
)
XML Serialization (using System.Xml.Serialization
)
Binary Serialization (using System.Runtime.Serialization.Formatters.Binary
)
Below are examples of each method.
Example 1: JSON Serialization and Deserialization
Using System.Text.Json
(Built-in in .NET Core 3.0+)
using System;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Create an object
var person = new Person { Name = "John", Age = 30 };
// Serialize to JSON
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine("Serialized JSON: " + jsonString);
// Deserialize from JSON
var deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Deserialized Object: Name = {deserializedPerson.Name}, Age = {deserializedPerson.Age}");
}
}
Using Newtonsoft.Json
(Popular third-party library)
using System;
using Newtonsoft.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Create an object
var person = new Person { Name = "John", Age = 30 };
// Serialize to JSON
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine("Serialized JSON: " + jsonString);
// Deserialize from JSON
var deserializedPerson = JsonConvert.DeserializeObject<Person>(jsonString);
Console.WriteLine($"Deserialized Object: Name = {deserializedPerson.Name}, Age = {deserializedPerson.Age}");
}
}
Example 2: XML Serialization and Deserialization
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()
{
// Create an object
var person = new Person { Name = "John", Age = 30 };
// Serialize to XML
var serializer = new XmlSerializer(typeof(Person));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, person);
string xmlString = writer.ToString();
Console.WriteLine("Serialized XML: " + xmlString);
// Deserialize from XML
using (var reader = new StringReader(xmlString))
{
var deserializedPerson = (Person)serializer.Deserialize(reader);
Console.WriteLine($"Deserialized Object: Name = {deserializedPerson.Name}, Age = {deserializedPerson.Age}");
}
}
}
}
Example 3: Binary Serialization and Deserialization
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable] // Mark the class as serializable
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Create an object
var person = new Person { Name = "John", Age = 30 };
// Serialize to binary
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, person);
byte[] binaryData = stream.ToArray();
Console.WriteLine("Object serialized to binary.");
// Deserialize from binary
stream.Seek(0, SeekOrigin.Begin); // Reset stream position
var deserializedPerson = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Deserialized Object: Name = {deserializedPerson.Name}, Age = {deserializedPerson.Age}");
}
}
}
Key Points to Remember
JSON is lightweight and widely used for web APIs.
XML is more verbose but human-readable and widely supported.
Binary is compact and efficient but not human-readable and less interoperable.
Always mark classes with [Serializable]
for binary serialization.
Use System.Text.Json
for modern .NET applications or Newtonsoft.Json
for more advanced features.
Comments
Post a Comment