Languages Knowledge Base

Parsing & Serializing JSON in C# with System.Text.Json

Complete C# JSON guide: JsonSerializer.Deserialize, JsonSerializer.Serialize with WriteIndented, and Newtonsoft.Json alternatives for .NET 6, 7, 8.

In C#, use System.Text.Json.JsonSerializer.Deserialize<T>(json) to parse JSON and JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true }) to produce pretty-printed JSON.

JSON in Modern C# (.NET 6+)

Since .NET Core 3.0, Microsoft ships System.Text.Json as the built-in high-performance JSON library. Newtonsoft.Json (Json.NET) remains popular for legacy projects.

System.Text.Json (Built-in, Recommended)

  • Parse: JsonSerializer.Deserialize<T>(jsonString)
  • Serialize: JsonSerializer.Serialize(obj)
  • Pretty print: Set JsonSerializerOptions { WriteIndented = true }
  • Camel case: Set PropertyNamingPolicy = JsonNamingPolicy.CamelCase
json
using System.Text.Json;

// Parse JSON string to C# object
var user = JsonSerializer.Deserialize<User>(jsonString);

// Serialize C# object to JSON
var json = JsonSerializer.Serialize(user);

// Pretty print with options
var options = new JsonSerializerOptions {
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var pretty = JsonSerializer.Serialize(user, options);

// Safe deserialization
try {
    var obj = JsonSerializer.Deserialize<MyType>(jsonText);
} catch (JsonException ex) {
    Console.WriteLine($"JSON error: {ex.Message}");
}

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

Should I use System.Text.Json or Newtonsoft.Json in .NET 6+?

System.Text.Json is the recommended default — it is faster and built-in. Use Newtonsoft only if you need specific features like non-public member serialization or dynamic typing.

How do I pretty print JSON in C#?

Pass new JsonSerializerOptions { WriteIndented = true } as the second argument to JsonSerializer.Serialize().

Related JSON Topics & Reference Articles