Working with JSON in C#: Serialization and Deserialization
Introduction
JSON (JavaScript Object Notation) has become the universal format for data exchange between applications, APIs, and services. As a C# developer, you will frequently need to convert objects to JSON and JSON back to objects. These processes are known as serialization and deserialization.
In this blog, we will explore everything you need to know about working with JSON in C#, using both
System.Text.Json (built-in) and Newtonsoft.Json (a popular third-party library).
What Is JSON?
JSON is a lightweight text-based data format used for structuring and exchanging data. It is easy to understand, fast to parse, and widely supported across programming languages.
Example JSON:
{
"Name": "John",
"Age": 30,
"Country": "India"
}
What Is Serialization?
Serialization is the process of converting a C# object into a JSON string so it can be stored, transmitted, or logged.
What Is Deserialization?
Deserialization is the opposite process — converting JSON string data back into a C# object.
Working with System.Text.Json (Recommended)
Introduced in .NET Core 3.0, System.Text.Json is the official Microsoft JSON library, optimized for performance.
✔ Define a C# Model
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
✔ Serialization Example
Person p = new Person { Name = "John", Age = 30 };
string json = JsonSerializer.Serialize(p);
Console.WriteLine(json);
✔ Deserialization Example
string json = "{ \"Name\": \"John\", \"Age\": 30 }";
Person p = JsonSerializer.Deserialize(json);
Console.WriteLine(p.Name);
✔ Formatting JSON Output
var options = new JsonSerializerOptions { WriteIndented = true };
string prettyJson = JsonSerializer.Serialize(p, options);
Console.WriteLine(prettyJson);
✔ Ignoring Properties
public class Person
{
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
}
Working with Newtonsoft.Json (Json.NET)
Newtonsoft.Json is the most widely used JSON library and offers powerful customization options.
✔ Serialization
Person p = new Person { Name = "John", Age = 30 };
string json = JsonConvert.SerializeObject(p, Formatting.Indented);
Console.WriteLine(json);
✔ Deserialization
string json = "{ \"Name\": \"John\", \"Age\": 30 }";
Person p = JsonConvert.DeserializeObject(json);
Console.WriteLine(p.Name);
✔ Ignoring Properties
public class Person
{
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
}
✔ Custom Property Names
public class Person
{
[JsonProperty("full_name")]
public string Name { get; set; }
}
Real-World Use Cases of JSON in C#
- Consuming REST APIs
- Sending data between microservices
- Saving configuration data
- Logging API responses
- Exporting reports
- Storing temporary application data
Common Pitfalls & Best Practices
✔ Avoid Case Sensitivity Issues
options.PropertyNameCaseInsensitive = true;
✔ Validate JSON Before Parsing
Always catch deserialization errors to avoid application crashes.
try
{
var person = JsonSerializer.Deserialize(json);
}
catch (JsonException ex)
{
Console.WriteLine("Invalid JSON!");
}
✔ Use PascalCase in C# and camelCase in JSON
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
Conclusion
JSON handling is an essential skill for C# developers, especially when working with APIs, databases, and modern applications. With powerful tools like System.Text.Json and Newtonsoft.Json, serialization and deserialization become simple and efficient.
Start applying these techniques in your projects and explore advanced topics like converters, polymorphic serialization, and handling large JSON files.
This Content Sponsored by SBO Digital Marketing. Mobile-Based Part-Time Job Opportunity by SBO! Earn money online by doing simple content publishing and sharing tasks. Here's how: Job Type: Mobile-based part-time work Work Involves: Content publishing Content sharing on social media Time Required: As little as 1 hour a day Earnings: ₹300 or more daily Requirements: Active Facebook and Instagram account Basic knowledge of using mobile and social media For more details: WhatsApp your Name and Qualification to 9025032394 a.Online Part Time Jobs from Home b.Work from Home Jobs Without Investment c.Freelance Jobs Online for Students d.Mobile Based Online Jobs e.Daily Payment Online Jobs Keyword & Tag: #OnlinePartTimeJob #WorkFromHome #EarnMoneyOnline #PartTimeJob #jobs #jobalerts #withoutinvestmentjob


0 Comments