DevToolsForYou

JSON Formatter, Minifier, and Validator in C# / .NET — Code Examples

JSON Formatter, Minifier, and Validator in C# / .NETUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

C# uses System.Text.Json (built-in since .NET 3.0) for JSON serialization. Use JsonSerializer.Serialize / Deserialize for typed objects.

C# / .NET
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

// Record type (C# 9+)
record User(
    [property: JsonPropertyName("name")] string Name,
    [property: JsonPropertyName("age")]  int Age
);

// Parse JSON string → object
var user = JsonSerializer.Deserialize<User>("""{"name":"Alice","age":30}""");
Console.WriteLine(user?.Name); // Alice

// Serialize object → JSON
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json); // {"name":"Alice","age":30}

// Pretty-print
var options = new JsonSerializerOptions { WriteIndented = true };
string pretty = JsonSerializer.Serialize(user, options);
Console.WriteLine(pretty);

// Camel case property names (common for APIs)
var apiOptions = new JsonSerializerOptions {
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

// Parse to JsonDocument (untyped, read-only)
using var doc = JsonDocument.Parse("""{"x":1,"y":2}""");
int x = doc.RootElement.GetProperty("x").GetInt32();
Console.WriteLine(x); // 1
Notes & gotchas
  • Reuse JsonSerializerOptions instances — they are thread-safe and expensive to create.
  • Use JsonDocument for read-only access to unknown JSON shapes; it is faster than deserializing to dynamic.
  • For complex scenarios (polymorphism, custom converters), add Newtonsoft.Json via NuGet — it offers more features than System.Text.Json.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages