Skip to main content
.NET Tips

Use JsonSerializer to Pretty-Print JSON in .NET

Formatting JSON as plain text with proper indentation can make it much easier to include in emails or other readable contexts. Here's a quick tip/guide on how to achieve that in .NET.

Christian Schou Køster

To pretty-print a JSON string in .NET and make it suitable for inclusion in an email, text page, a string, or any other thing, you can format the JSON with proper indentation and ensure it is styled as plain text for easy readability.

Code Example

Let's have a look at how we can implement this method on strings in our code.

using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        string jsonString = "{\"name\":\"Christian\",\"age\":28,\"country\":\"Denmark\"}";
        
        // Pretty-print the JSON string
        string prettyJson = PrettyPrintJson(jsonString);

        // Print the result
        Console.WriteLine(prettyJson);
    }

    static string PrettyPrintJson(string jsonString)
    {
        var jsonElement = JsonDocument.Parse(jsonString).RootElement;
        return JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
    }
}

What happens above? 🤔 Let me explain.

  1. Parsing the JSON text - The JsonDocument.Parse method reads and parses the JSON string.
  2. Serialization with Indentation - The JsonSerializer.Serialize method outputs the JSON string with indentation by setting WriteIndented to true in the options.

As An Extension Method

using System.Text.Json;

namespace <YourNameSpace-UPDATE-ME>;

public static class StringExtensions
{   
    /// <summary>
    ///     Pretty prints a JSON string.
    /// </summary>
    /// <param name="jsonString"></param>
    /// <returns></returns>
    public static string PrettyPrintJson(this string jsonString)
    {
        JsonElement jsonElement = JsonDocument.Parse(jsonString).RootElement;
        return JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
    }
}

With this, you can easily extend logic on your default strings to return a string in JSON format in a pretty way. 👌

I hope you solved a problem in your code with this short tutorial. If you have any questions, please let me know in the comments below. ✌️

Resources

System.Text.Json Namespace
Provides high-performance, low-allocating, and standards-compliant capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON text and deserializing JSON text to objects, with UTF-8 support built-in. It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM) for random access of the JSON elements within a structured view of the data.
Christian Schou Køster