How to Parse JSON in C#
Modern .NET includes System.Text.Json. Use JsonSerializer to bind JSON to classes/records, or JsonDocument for read-only DOM access.
Deserialize to a class
JsonSerializer.Deserialize maps JSON to a type. Property name matching is case-insensitive by default in ASP.NET.
csharp
record User(string Name, string[] Roles);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
User? u = JsonSerializer.Deserialize<User>(text, options);
Console.WriteLine(u?.Name);Read with JsonDocument
JsonDocument gives fast, read-only access without a class.
csharp
using var doc = JsonDocument.Parse(text);
JsonElement root = doc.RootElement;
string name = root.GetProperty("name").GetString()!;Serialize and pretty-print
Set WriteIndented for readable output.
csharp
var json = JsonSerializer.Serialize(u);
var pretty = JsonSerializer.Serialize(u,
new JsonSerializerOptions { WriteIndented = true });