Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

C# and .NET JSON Formatter Implementation

If you need to format a JSON string in C#, the reliable pattern is simple: parse the JSON, then serialize it back out either with indentation for readability or without indentation for compact output. For modern .NET apps, System.Text.Json is the default choice. For older codebases or projects that already depend on Json.NET, Newtonsoft.Json is still a solid option.

Search visitors usually want one of three things here: a quick C# pretty-print helper, the exact Newtonsoft.Json equivalent, or a small CLI formatter they can drop into a console app. This page focuses on those answers first, then covers the edge cases that usually cause formatting code to fail.

  • Use System.Text.Json for new .NET work unless you already have a strong reason to stay on Json.NET.
  • Parse existing JSON strings before formatting them. Serializing a raw string directly will quote the string instead of reformatting the JSON inside it.
  • Use pretty-printing for logs, debugging, docs, and copied API responses. Use compact output when size matters.

Quick Answer for Modern .NET

For most current C# projects, this is the formatter helper you want. It handles both pretty print and minify for an existing JSON string using System.Text.Json.

Example: Format a JSON string in C# with System.Text.Json

using System.Text.Json;

public static class JsonFormatter
{
    private static readonly JsonSerializerOptions PrettyOptions = new()
    {
        WriteIndented = true,
#if NET9_0_OR_GREATER
        IndentCharacter = ' ',
        IndentSize = 2
#endif
    };

    public static string PrettyPrint(string json)
    {
        using JsonDocument document = JsonDocument.Parse(json);
        return JsonSerializer.Serialize(document.RootElement, PrettyOptions);
    }

    public static string Minify(string json)
    {
        using JsonDocument document = JsonDocument.Parse(json);
        return JsonSerializer.Serialize(document.RootElement);
    }
}

That covers the common search intent behind queries like c# format json string and c# json formatter. If the input is already a C# object rather than a JSON string, skip the parse step and call JsonSerializer.Serialize(objectValue, PrettyOptions) directly.

System.Text.Json Notes That Matter in 2026

System.Text.Json is the built-in JSON stack for modern .NET and is usually the best default for a formatter. It gives you good performance, fewer dependencies, and straightforward APIs for both DOM-style and streaming scenarios.

  • Pretty-printing: Set WriteIndented = true when serializing.
  • Minifying: The default serializer output is compact, so no special setting is required.
  • Current .NET 9 detail: JsonSerializerOptions now lets you control indentation style with IndentCharacter and IndentSize, which is useful if your team wants tabs or 4-space indentation instead of the default style.
  • DOM choice: JsonDocument is read-only and a good fit when you only need to reformat. JsonNode is easier if you want to edit values before writing the JSON back out.
  • Reuse options: Reuse JsonSerializerOptions instances in hot paths instead of creating new ones for every call.

For formatting an arbitrary JSON string, JsonDocument is typically the cleanest choice because it validates the input and avoids mapping the payload to C# classes you do not need.

Example: Accept comments and trailing commas before formatting

using System.Text.Json;

public static string PrettyPrintLooseJson(string json)
{
    var documentOptions = new JsonDocumentOptions
    {
        CommentHandling = JsonCommentHandling.Skip,
        AllowTrailingCommas = true
    };

    using JsonDocument document = JsonDocument.Parse(json, documentOptions);

    var serializerOptions = new JsonSerializerOptions
    {
        WriteIndented = true
    };

    return JsonSerializer.Serialize(document.RootElement, serializerOptions);
}

This is useful when the input came from config-like JSON, test fixtures, or copied API samples that include comments or dangling commas. The output is still standard JSON, so comments and trailing commas are removed during formatting.

Newtonsoft.Json Pretty Print and Compact

If your project already uses Newtonsoft.Json, stick with it for formatting. The API is still concise, and this path directly answers searches like newtonsoft json pretty print.

Example: Pretty-print and minify with Newtonsoft.Json

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static class NewtonsoftJsonFormatter
{
    public static string PrettyPrint(string json)
    {
        JToken token = JToken.Parse(json);
        return token.ToString(Formatting.Indented);
    }

    public static string Minify(string json)
    {
        JToken token = JToken.Parse(json);
        return token.ToString(Formatting.None);
    }
}

A useful Json.NET detail: JToken.ToString() without arguments already returns indented JSON. If you want the compact form explicitly, use Formatting.None.

Use Json.NET when you are maintaining legacy .NET Framework code, already depend on JObject / JArray, or need ecosystem features your codebase already relies on. For brand-new apps that only need formatting, System.Text.Json is usually the cleaner default.

Simple CLI JSON Formatter in C#

For a small console utility, read from a file or standard input, parse once, and write the normalized JSON to standard output. This is the clean answer for developers looking for a C# CLI JSON formatter.

Example: Minimal console formatter

using System.Text.Json;

if (args.Length == 0)
{
    Console.Error.WriteLine("Usage: jsonfmt <path-or-> [--minify]");
    return 1;
}

string input = args[0] == "-"
    ? Console.In.ReadToEnd()
    : File.ReadAllText(args[0]);

bool minify = args.Contains("--minify");

try
{
    using JsonDocument document = JsonDocument.Parse(input);

    var options = new JsonSerializerOptions
    {
        WriteIndented = !minify
    };

    Console.WriteLine(JsonSerializer.Serialize(document.RootElement, options));
    return 0;
}
catch (JsonException ex)
{
    Console.Error.WriteLine("Invalid JSON: " + ex.Message);
    return 1;
}

If you need table output in a CLI, that is a separate problem from formatting. JSON formatters preserve the JSON structure; they do not flatten nested objects into columns. For tabular output, deserialize into a typed model or transform the JSON first.

Common Mistakes and Troubleshooting

  • Do not serialize a raw JSON string directly. This is the most common mistake. JsonSerializer.Serialize(jsonString) and JsonConvert.SerializeObject(jsonString)will escape and quote the entire string instead of formatting its contents.
  • Invalid JSON is still invalid after formatting. Single quotes, broken escaping, missing commas, and extra wrapper text will throw parse errors. If you copied the data from logs, SoapUI, or a test harness, make sure you are passing only the raw JSON body.
  • Formatting is not byte-for-byte preservation. A formatter rewrites whitespace and may also normalize escape sequences or remove tolerated extras like comments and trailing commas.
  • Very large payloads need different tactics. For large files or performance-sensitive loops, prefer streaming APIs like Utf8JsonWriter rather than repeatedly building an in-memory DOM just to make logs look nicer.

Which Formatter Should You Use?

  • Choose System.Text.Json for new .NET applications, lightweight dependencies, and strong default performance.
  • Choose Newtonsoft.Json when the codebase already uses Json.NET heavily or relies on its DOM and customization model.
  • Choose a CLI wrapper around System.Text.Json when you want a quick formatter for scripts, pipelines, or local tooling.

Conclusion

The best C# JSON formatter implementation is usually just parse, validate, and serialize with the right indentation settings. In current .NET, System.Text.Json is the default answer for most apps, while Newtonsoft.Json remains a practical option for existing codebases and Json.NET-heavy workflows. If your main goal is simply to pretty-print a string, the small helper methods above are enough.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool