New Format Options of System.Text.Json with .NET 9

New Format Options of System.Text.Json with .NET 9

New Format Options of System.Text.Json with .NET 9

With .NET 9, Microsoft has added new options to the System.Text.Json library to format the output of JSON objects - features that, in my opinion, should have been available with day 1.

Default Output

Given is the following code that creates a Person object and serializes it with the default options.

using System;
using System.Text.Json;
					
public class Program
{
   public static void Main()
   {
      Person person = new("Bruce Wayne", new(1915, 4, 7));
   
      string jsonString = JsonSerializer.Serialize(person);
   
      Console.WriteLine(jsonString);
   }

   public sealed record class Person(string Name, DateOnly Birthday);
}

The output will be:

{"Name":"Bruce Wayne","Birthday":"1915-04-07"}

This output is very efficient; no additional line breaks or indentations are used to improve readability - but it is just that: very efficient but difficult for humans to read.

Intended Output

From .NET 3.0 and upwards, we have the JsonSerializerOptions class, with which we can specify options; for example, the WriteIndented option, which formats the output.

JsonSerializerOptions options = new () { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(person, options);
{
 "Name": "Bruce Wayne",
 "Birthday": "1915-04-07"
}

This gives us an output that is easier for people to read.

Defaults

But which output formats are actually the right ones for the respective situation?

With .NET 9, the .NET team has now significantly improved and simplified the output. There is now the option JsonSerializerDefaults.Web with which the developer no longer has to worry about which formats are common - there are now predefined standards.

JsonSerializerOptions options = new(JsonSerializerDefaults.Web);
string jsonString = JsonSerializer.Serialize(person, options);

The current implementation of JsonSerializerDefaults.Web is the only one of the enum apart from General; and this is again optimized for web output.

{"Name":"Bruce Wayne","Birthday":"1915-04-07"}

So if you need an output for the web, you can now simply use the option JsonSerializerDefaults.Web and get an output that is optimized for the web. You still have to take care of the more human-readable output yourself.

JsonSerializerOptions options = new () { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(person, options);

However, I assume that we will see more entries in the JsonSerializerDefaults enum in the future, which will provide further standard output formats and thus make it easier for the developer to choose the right output - and to further standardize the output.