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.
- Parsing the JSON text - The
JsonDocument.Parse
method reads and parses the JSON string. - Serialization with Indentation - The
JsonSerializer.Serialize
method outputs the JSON string with indentation by settingWriteIndented
totrue
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
