Serialization and Deserialization are very common interview questions in .NET.
🔹 What is Serialization?
Serialization is the process of converting an object into a format that can be:
-
Stored in file
-
Sent over network
-
Saved in database
-
Cached
Usually converted into:
-
JSON
-
XML
-
Binary
Example
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
Serialization converts this object:
Employee emp = new Employee { Id = 1, Name = "Sampath" };
Into JSON:
{
"Id": 1,
"Name": "Sampath"
}
🔹 What is Deserialization?
Deserialization is the reverse process.
It converts:
👉 JSON / XML → Object
Example:
{
"Id": 1,
"Name": "Sampath"
}
Converted back into:
Employee emp = new Employee();
🔹 Real World Example
When you call an API:
API Response (JSON)
{
"id": 10,
"title": "Article Title"
}
Your application converts it to:
Article article = response;
👉 This is Deserialization
🔹 Serialization Example in .NET
Using System.Text.Json
using System.Text.Json;
Employee emp = new Employee { Id = 1, Name = "Sampath" };
string json = JsonSerializer.Serialize(emp);
Console.WriteLine(json);
🔹 Deserialization Example
string json = "{\"Id\":1,\"Name\":\"Sampath\"}";
Employee emp = JsonSerializer.Deserialize<Employee>(json);
🔹 Another Popular Library
Many developers also use
Newtonsoft.Json
Example:
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(emp);
Employee emp = JsonConvert.DeserializeObject<Employee>(json);
🔹 Why Do We Use Serialization?
We use serialization for:
-
Web APIs
-
Microservices communication
-
Saving data to files
-
Caching (Redis)
-
Session storage
🔹 Interview One-Line Answer
Serialization → Convert Object → JSON/XML
Deserialization → Convert JSON/XML → Object
🔹 Interview Follow-Up Questions
Which is faster?
✅ System.Text.Json (faster, built-in)
Which is more flexible?
✅ Newtonsoft.Json (more features)
🔹 Very Common Interview Example
ASP.NET Core Controller:
[HttpPost]
public IActionResult Save(Employee emp)
{
return Ok(emp);
}
Here:
-
Request JSON → Deserialization
-
Response Object → Serialization
