Ignoring properties conditionally in JSON serialization with System.Text.Json
Posted: (EET/GMT+2)
The System.Text.Json namespace today contains nice JSON serialization/deserialization support, and in new applications, you might prefer the built-in serializer over for example the Newtonsoft parser. At this writing, Microsoft's implementation is (has?) become the default JSON engine in .NET, and it includes a neat feature that lets you ignore properties based on runtime conditions. This is useful when your object model contains values you don't always want to expose.
You can configure conditional ignoring using [JsonIgnore] attributes or by
setting JsonIgnoreCondition directly.
For example:
public class User
{
public string Name { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? PhoneNumber { get; set; }
}
With this configuration, if PhoneNumber is null, the property won't appear in the output JSON at all:
{ "Name": "Jane" }
You can also ignore properties when writing default values:
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
This is handy in DTOs where you want compact output and want to avoid exposing fields that don't carry meaningful data.
The new ignore conditions make System.Text.Json flexible enough for typical
web APIs, without needing custom converters or special serializer settings.