C# VS2026
Lesson 24 of 30

JSON Serialisation with System.Text.Json

C# in Visual Studio 2026 — a hands-on guide for developers at every level.

JSON in Modern C#

System.Text.Json is the built-in, high-performance JSON library included with .NET. No additional packages needed.

Serialisation – Object to JSON

using System.Text.Json;

record Person(string Name, int Age, string City);

var person = new Person("Alice", 30, "London");

var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(person, options);
Console.WriteLine(json);

Deserialisation – JSON to Object

string jsonStr = """{"Name":"Bob","Age":25,"City":"Paris"}""";
Person? p = JsonSerializer.Deserialize<Person>(jsonStr);
Console.WriteLine($"{p?.Name} from {p?.City}");

Collections and JSON

var people = new List<Person>
{
    new("Alice", 30, "London"),
    new("Bob",   25, "Paris")
};

string json = JsonSerializer.Serialize(people);
List<Person>? loaded = JsonSerializer.Deserialize<List<Person>>(json);
Console.WriteLine(loaded?.Count);  // 2

Reading/Writing JSON Files

// Write
await using var writeStream = File.Create("data.json");
await JsonSerializer.SerializeAsync(writeStream, people);

// Read
await using var readStream = File.OpenRead("data.json");
var loaded = await JsonSerializer.DeserializeAsync<List<Person>>(readStream);