JSON Serialization & System.Text.Json Masterclass
Welcome to Phase 9 (Chapter 27): C# JSON Serialization, Deserialization & System.Text.Json Masterclass! JSON (JavaScript Object Notation) is the universal standard data exchange format used in REST APIs, cloud services, and configuration files. In this chapter, we master serialization (C# object โ JSON string), deserialization (JSON string โ C# object), JsonSerializer, JsonSerializerOptions, nullable handling, custom converters, and modeling real API payloads.
using System.Text.Json;
// 1. Anonymous object serialization
var student = new
{
Name = "Ravi",
Age = 20,
Course = "C# Masterclass"
};
string json = JsonSerializer.Serialize(student);
Console.WriteLine($"Serialized JSON: {json}");
// Output: {"Name":"Ravi","Age":20,"Course":"C# Masterclass"}
public class StudentDto
{
public string Name { get; set; } = "";
public int Age { get; set; }
public string? Course { get; set; }
}
string jsonInput = """{"Name":"Alice","Age":22,"Course":"ASP.NET Core"}""";
StudentDto? deserializedStudent = JsonSerializer.Deserialize<StudentDto>(jsonInput);
Console.WriteLine($"Name: {deserializedStudent?.Name}, Age: {deserializedStudent?.Age}");
// Serialize with formatting options
JsonSerializerOptions options = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
string prettyJson = JsonSerializer.Serialize(deserializedStudent, options);
Console.WriteLine(prettyJson);
var products = new List<object>
{
new { Id = 1, Name = "Laptop", Price = 75000 },
new { Id = 2, Name = "Mouse", Price = 1200 },
new { Id = 3, Name = "Keyboard", Price = 2500 }
};
string json = JsonSerializer.Serialize(products, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync("products.json", json);
Console.WriteLine("Products saved to products.json!");
Q1: What is the difference between System.Text.Json and Newtonsoft.Json?
System.Text.Json is Microsoft's built-in high-performance JSON library included in .NET Core 3+ with zero external dependencies. Newtonsoft.Json (Json.NET) is a third-party NuGet package with richer feature support (custom converters, LINQ-to-JSON, etc.) and is preferred for complex legacy integration scenarios.
Q2: What does JsonNamingPolicy.CamelCase do?
It transforms C# PascalCase property names (e.g., FirstName) to JSON camelCase (e.g., firstName) automatically during serialization, matching REST API conventions.