How to Parse JSON in C#

← All guides

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 });

Frequently Asked Questions

System.Text.Json is built in, fast, and recommended for new code. Newtonsoft (Json.NET) is more flexible for edge cases and legacy projects.

Use the JSON to C# tool to generate classes for System.Text.Json or Newtonsoft from a sample JSON document.

JSON keys must match property names. Enable PropertyNameCaseInsensitive or use [JsonPropertyName] attributes to map differing names.

Related Tools