JSON Serialization & System.Text.Json Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 27 of 35 ๐Ÿ“‚ Phase 9: Exceptions, Files & JSON ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: JSON Basics ยท Serialization ยท Deserialization ยท JsonSerializer ยท JsonSerializerOptions ยท CamelCase Policy ยท JSON Arrays ยท Async JSON ยท Custom Converters

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.

1JSON Serialization & Deserialization with JsonSerializer
C# โ€” Serialize & Deserialize JSON โ–ถ Run in Compiler
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"}
2Deserializing Typed C# Objects from JSON
C# โ€” Deserialization with Typed Classes โ–ถ Run in Compiler
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);
3JSON Arrays & Async File JSON
C# โ€” JSON Arrays & Async Save โ–ถ Run in Compiler
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!");
4Technical FAQs

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.