C#
.NET
JSON formatting
JSON indentation
code formatting

How do I get formatted and indented JSON in .NET using C?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Indented JSON is useful when people need to read it. Logs, diagnostics, saved snapshots, configuration dumps, and admin tools are all easier to inspect when the output is formatted instead of minified.

In .NET, the usual answer is either System.Text.Json or Newtonsoft.Json. Both support pretty printing, but the code you choose should match the serializer the project is already using.

Format JSON With System.Text.Json

In modern .NET, System.Text.Json is the default serializer for many applications. To produce indented output, enable WriteIndented:

csharp
1using System;
2using System.Text.Json;
3
4public sealed class BuildInfo
5{
6    public string Service { get; set; } = string.Empty;
7    public string Version { get; set; } = string.Empty;
8    public DateTime DeployedAtUtc { get; set; }
9}
10
11public static class Program
12{
13    public static void Main()
14    {
15        var payload = new BuildInfo
16        {
17            Service = "billing-api",
18            Version = "2.4.1",
19            DeployedAtUtc = DateTime.UtcNow
20        };
21
22        var options = new JsonSerializerOptions
23        {
24            WriteIndented = true
25        };
26
27        string json = JsonSerializer.Serialize(payload, options);
28        Console.WriteLine(json);
29    }
30}

If you are serializing your own objects, this is the simplest and cleanest path.

Reformat Existing JSON Text

Sometimes you already have JSON as a string and only want a readable version. In that case, parse the string and serialize it again:

csharp
1using System;
2using System.Text.Json;
3
4public static class JsonFormatter
5{
6    public static string Prettify(string rawJson)
7    {
8        using JsonDocument doc = JsonDocument.Parse(rawJson);
9        return JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions
10        {
11            WriteIndented = true
12        });
13    }
14}
15
16public static class Program
17{
18    public static void Main()
19    {
20        string minified = "{\"ok\":true,\"items\":[1,2,3],\"meta\":{\"env\":\"prod\"}}";
21        Console.WriteLine(JsonFormatter.Prettify(minified));
22    }
23}

This is a practical pattern for debug tools, command-line utilities, and log viewers.

Use Newtonsoft.Json When the Project Already Depends on It

Many established .NET codebases still use Json.NET. The equivalent formatting option is Formatting.Indented:

csharp
1using System;
2using Newtonsoft.Json;
3
4public sealed class Person
5{
6    public string Name { get; set; } = string.Empty;
7    public int Age { get; set; }
8}
9
10public static class Program
11{
12    public static void Main()
13    {
14        var person = new Person { Name = "Riley", Age = 33 };
15        string json = JsonConvert.SerializeObject(person, Formatting.Indented);
16        Console.WriteLine(json);
17    }
18}

If your project already relies on Json.NET for custom converters or existing contracts, there is no reason to switch libraries just to indent JSON.

Choose Readability Intentionally

Pretty printing is mainly for humans. It adds whitespace, which increases size. That is perfect for logs, snapshots, and debugging output, but it is not always the right default for high-volume API responses.

A useful rule is:

  • format JSON when humans are expected to read it
  • keep JSON compact when the main consumer is another machine and bandwidth matters

That keeps your serialization policy intentional instead of accidental.

Handle Invalid JSON Input

If you are reformatting raw JSON text, remember that a formatter is not a repair tool. Invalid JSON should raise an error, not be silently guessed into shape.

csharp
1using System;
2using System.Text.Json;
3
4try
5{
6    Console.WriteLine(JsonFormatter.Prettify("{invalid json"));
7}
8catch (JsonException ex)
9{
10    Console.WriteLine($"Invalid JSON: {ex.Message}");
11}

That behavior is exactly what you want in tools that need to distinguish bad input from formatting requests.

Common Pitfalls

The most common mistake is trying to pretty-print data that is not valid JSON. If parsing fails, the problem is the input, not the indentation code.

Another common issue is mixing System.Text.Json and Newtonsoft.Json casually in the same pipeline. The output may differ in property naming, null handling, or date formatting, which can be surprising.

Developers also sometimes leave indentation enabled everywhere, including large production responses where nobody reads the whitespace. That adds overhead without providing much value.

Finally, do not confuse "pretty" with "canonical." Indented JSON is easier for humans to read, but it is not a stable canonical representation for signing or hashing.

Summary

  • Use WriteIndented = true with System.Text.Json for formatted JSON in modern .NET.
  • Use Formatting.Indented if your project already uses Json.NET.
  • Reformat existing JSON text by parsing it first and serializing it again.
  • Pretty printing is mainly for human-facing output such as logs and tools.
  • Treat invalid JSON as an error instead of expecting the formatter to repair it.

Course illustration
Course illustration

All Rights Reserved.