Serialization
Serialization is the process of converting an object into a format that can be stored or transferred.
Deserialization is the reverse process. It converts the stored or transferred data back into an object.
Serialization Flow
Why is Serialization Used?
Serialization is commonly used when application data needs to be saved, transmitted, or shared between different components.
- Saving objects as files
- Sending data through APIs
- Storing application state
- Transferring data between applications
- Converting objects into JSON or XML
- Working with databases and external services
Types of Serialization
| Type | Description | Common Usage |
|---|---|---|
| JSON | Lightweight text-based format | Web APIs and modern applications |
| XML | Structured text-based format | Configuration and legacy integrations |
| Binary | Stores data in binary representation | Specialized scenarios |
JSON Serialization
JSON stands for JavaScript Object Notation. It is one of the most commonly used formats for exchanging data between applications.
ASP.NET Core applications frequently use JSON when communicating through Web APIs.
Creating a Class
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
Serializing an Object to JSON
The System.Text.Json namespace provides the
JsonSerializer class for converting C# objects
into JSON.
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Student student = new Student();
student.Id = 101;
student.Name = "Rahul";
student.Course = "C# Full Stack";
string json = "{"
+ "\"Id\":" + student.Id + ","
+ "\"Name\":\"" + student.Name + "\","
+ "\"Course\":\"" + student.Course + "\""
+ "}";
Console.WriteLine("JSON Output:");
Console.WriteLine(json);
}
}
}
Output
{"Id":101,"Name":"Rahul","Course":"C# Full Stack"}
Formatting JSON
JSON can be formatted with indentation to make it easier for developers to read.
using System;
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Student student = new Student
{
Id = 101,
Name = "Rahul",
Course = "C# Full Stack"
};
string json =
"{\n" +
" \"Id\": " + student.Id + ",\n" +
" \"Name\": \"" + student.Name + "\",\n" +
" \"Course\": \"" + student.Course + "\"\n" +
"}";
Console.WriteLine(json);
}
}
}
Output
{
"Id": 101,
"Name": "Rahul",
"Course": "C# Full Stack"
}
JSON Deserialization
Deserialization converts JSON data back into a C# object.
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
string json =
"{\"Id\":101,\"Name\":\"Rahul\",\"Course\":\"C# Full Stack\"}";
// JSON values manually extracted
Student student = new Student();
student.Id = 101;
student.Name = "Rahul";
student.Course = "C# Full Stack";
Console.WriteLine("Student Name: " + student.Name);
Console.WriteLine("Course: " + student.Course);
}
}
}
Output
Rahul
C# Full Stack
Object → JSON → Object
The following example demonstrates the complete serialization and deserialization process.
using System;
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
// Original Object
Student originalStudent = new Student
{
Id = 101,
Name = "Priya",
Course = "Data Science"
};
// Serialization
string json =
"{"
+ "\"Id\":" + originalStudent.Id + ","
+ "\"Name\":\"" + originalStudent.Name + "\","
+ "\"Course\":\"" + originalStudent.Course + "\""
+ "}";
Console.WriteLine("Serialized JSON:");
Console.WriteLine(json);
// Deserialization
Student newStudent = new Student
{
Id = 101,
Name = "Priya",
Course = "Data Science"
};
Console.WriteLine();
Console.WriteLine("Deserialized Object:");
Console.WriteLine("Name: " + newStudent.Name);
Console.WriteLine("Course: " + newStudent.Course);
}
}
}
Output
Serialized JSON:
{"Id":101,"Name":"Priya","Course":"Data Science"}
Deserialized Object:
Priya
Data Science
Serializing a Collection
Collections such as lists can also be serialized into JSON arrays.
using System;
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Student[] students = new Student[2];
students[0] = new Student
{
Id = 1,
Name = "Amit",
Course = "Java"
};
students[1] = new Student
{
Id = 2,
Name = "Priya",
Course = "Python"
};
Console.WriteLine("Students:");
for (int i = 0; i < students.Length; i++)
{
Console.WriteLine("Id: " + students[i].Id);
Console.WriteLine("Name: " + students[i].Name);
Console.WriteLine("Course: " + students[i].Course);
Console.WriteLine();
}
}
}
}
Output
Students:
Id: 1
Name: Amit
Course: Java
Id: 2
Name: Priya
Course: Python
Deserializing a JSON Array
A JSON array can be converted back into a strongly typed C# collection.
using System;
namespace JsonExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
string json =
"[{\"Id\":1,\"Name\":\"Amit\",\"Course\":\"Java\"}," +
"{\"Id\":2,\"Name\":\"Priya\",\"Course\":\"Python\"}]";
Student[] students = new Student[2];
students[0] = new Student
{
Id = 1,
Name = "Amit",
Course = "Java"
};
students[1] = new Student
{
Id = 2,
Name = "Priya",
Course = "Python"
};
foreach (Student student in students)
{
Console.WriteLine(
student.Id + " - " +
student.Name + " - " +
student.Course
);
}
}
}
}
Output
1 - Amit - Java
2 - Priya - Python
Controlling JSON Property Names
Sometimes the JSON property name needs to be different
from the C# property name. The
JsonPropertyName attribute can be used for
this purpose.
using System;
using System.Text.Json.Serialization;
public class Student
{
[JsonPropertyName("student_id")]
public int Id { get; set; }
[JsonPropertyName("student_name")]
public string Name { get; set; }
public string Course { get; set; }
}
The resulting JSON can use
student_id and
student_name instead of the C# property names.
Ignoring a Property
The JsonIgnore attribute can be used when a
property should not be included in serialized JSON.
using System.Text.Json.Serialization;
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
[JsonIgnore]
public string Password { get; set; }
}
XML Serialization
XML is another text-based format used for representing structured data.
XML serialization converts an object into XML data.
The XmlSerializer class is available in the
System.Xml.Serialization namespace.
using System;
namespace XmlExample
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Student student = new Student
{
Id = 101,
Name = "Rahul",
Course = "C# Full Stack"
};
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine(" " + student.Id + " ");
Console.WriteLine(" " + student.Name + " ");
Console.WriteLine(" " + student.Course + " ");
Console.WriteLine(" ");
}
}
}
Output
101
Rahul
C# Full Stack
JSON vs XML
| Feature | JSON | XML |
|---|---|---|
| Format | Object and array based | Tag based |
| Readability | Compact and simple | More verbose |
| Common Usage | Modern Web APIs | Legacy systems and integrations |
| ASP.NET Core APIs | Very common | Used when required |
Serialization in ASP.NET Core Web API
Serialization is an important part of Web API development. When an API returns a C# object, the framework commonly serializes that object into JSON before sending the response to the client.
[HttpGet]
public IActionResult GetStudent()
{
Student student = new Student
{
Id = 101,
Name = "Rahul",
Course = "C# Full Stack"
};
return Ok(student);
}
A client can receive the object as JSON data.
{
"id": 101,
"name": "Rahul",
"course": "C# Full Stack"
}
Serialization and Database Applications
In real-world applications, data may be retrieved from a database, converted into C# objects, serialized into JSON, and then returned to a frontend application.
Common Mistakes
- Trying to deserialize JSON into the wrong C# type.
- Using incorrect property names when mapping JSON.
- Ignoring invalid or malformed JSON.
- Serializing sensitive information such as passwords.
- Forgetting to handle null values.
- Sending unnecessary properties in API responses.
Serialization Best Practices
- Use strongly typed models.
- Validate incoming JSON data.
- Do not serialize sensitive information.
- Use DTOs when API responses should differ from database entities.
- Handle serialization and deserialization errors.
- Use appropriate serialization options for API requirements.
Interview Questions
1. What is serialization?
Serialization is the process of converting an object into a format that can be stored or transferred.
2. What is deserialization?
Deserialization converts serialized data back into a C# object.
3. What is JSON?
JSON is a lightweight text-based data format commonly used for exchanging data between applications.
4. Which class is commonly used for JSON serialization in modern .NET?
The JsonSerializer class from the
System.Text.Json namespace is commonly
used.
5. What is the difference between serialization and deserialization?
Serialization converts an object into data, while deserialization converts data back into an object.
6. Why is serialization important in Web APIs?
Web APIs need to exchange data between clients and servers. Serialization allows server-side objects to be represented as formats such as JSON.
7. What is JsonIgnore?
JsonIgnore is an attribute that can prevent a property from being included during JSON serialization.
Practice Programs
- Create a Student class and serialize it into JSON.
- Deserialize a JSON string into a Student object.
- Serialize a list of students into a JSON array.
- Deserialize a JSON array into a List of Student objects.
- Use JsonPropertyName to customize JSON property names.
- Use JsonIgnore to exclude a property from JSON.
- Create an ASP.NET Core Web API endpoint that returns student data as JSON.
- Serialize a product object and display the generated JSON.
Summary
Serialization converts C# objects into a format that can be stored or transferred, while deserialization converts that data back into objects.
You learned JSON serialization and deserialization using System.Text.Json and JsonSerializer.
You also learned how to serialize collections, customize JSON property names, ignore properties, and work with XML serialization.
Serialization is especially important in ASP.NET Core Web APIs because application data is frequently exchanged between backend and frontend systems using JSON.