Common Newtonsoft.Json options in System.Text.Json

If you’re switching from Newtonsoft.Json to System.Text.Json (or vice versa), you may be wondering how to specify the common options you’re used to using in Newtonsoft. For example, how do you specify the equivalent of Newtonsoft.Json.Converters.StringEnumConverter in System.Text.Json?

The following table shows a few common serialization options used in Newtonsoft.Json and their equivalents in System.Text.Json.

Show enum name instead of numberNewtonsoft.Json.Converters.StringEnumConverterSystem.Text.Json.Serialization.JsonStringEnumConverter
IndentFormatting = Formatting.IndentedWriteIndented = true
Ignore nullsNullValueHandling = NullValueHandling.IgnoreIgnoreNullValues = true

The way you specify options in these two serializers is quite similar. In both, you can pass in converters – such as the StringEnumConverter. Newtonsoft tends to use enums for options, whereas System.Text.Json tends to use bools.

The example below demonstrates how to serialize an object, using both Newtonsoft and System.Text.Json, with all of the common options mentioned above. They produce the exact same JSON string, as expected.

Example – serializing with the common options

I have the following object that I want to serialize:

var detroitLions = new NFLTeam()
	City = "Detroit",
	Name = "Lions",
	Conference = Conference.NFC,
	Division = Division.North,
	Notes = null

I want to show the enum names instead of their numeric values, ignore null values, and indent the output. I want it to look like the following:

  "City": "Detroit",
  "Name": "Lions",
  "Conference": "NFC",
  "Division": "North"

Serializing with Newtonsoft.Json

  • using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(detroitLions, 
	new JsonSerializerSettings()
	NullValueHandling = NullValueHandling.Ignore,
	Formatting = Formatting.Indented,
	Converters = { new Newtonsoft.Json.Converters.StringEnumConverter() }

Serializing with System.Text.Json

  • using System.Text.Json;
  • using System.Text.Json.Serialization;
var jsonOptions = new JsonSerializerOptions()
	WriteIndented = true,
	IgnoreNullValues = true,
jsonOptions.Converters.Add(new JsonStringEnumConverter());
var json = JsonSerializer.Serialize<NFLTeam>(detroitLions, jsonOptions);

Leave a Comment