JsonIgnoreCondition.WhenWritingNull: Ignore Null in C#

You serialize an object with System.Text.Json and the output is full of "note": null. To ignore null properties, set JsonIgnoreCondition.WhenWritingNull: either as DefaultIgnoreCondition on JsonSerializerOptions for every property, or with [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] on a single property. This guide shows both, the ASP.NET Core global setting, and what to do about empty strings and empty lists, which this setting does not remove.

Every snippet was compiled and run on .NET SDK 10.0.401 on macOS, and the output shown is the real output. See the end of the post for what was not tested.

Animation of one C# Order object serialized four ways with System.Text.Json: default options, WhenWritingNull, WhenWritingDefault and a contract modifier, showing which properties disappear from the JSON

Diagram built from the real output of the test program below, not a screenshot.

Which setting should you use?

JsonIgnoreCondition has four values. Two matter for hiding null:

ValueProperty is skipped when writing ifUse it for
WhenWritingNullit is a null reference type or a null nullable value typeThe usual case: hide nulls
WhenWritingDefaultit is null, or a value type holds its default (0, false)Hide nulls and zeros. Careful: a real 0 or false disappears too
Nevernever; always writtenOverride a global ignore for one property
Alwaysalways skipped (the default for [JsonIgnore] without a condition)Hide a property completely

This follows the Microsoft documentation on ignoring properties. Pick the scope by how many places need it: one call (options), one property (attribute) or the whole app (global).

Prerequisites and test class

You need the .NET SDK (the examples use .NET 10, and the same API exists in .NET 6 and later). No NuGet package is required because System.Text.Json ships with the runtime. The class used in every example:

public class Order
{
    public string Id { get; set; } = "";
    public string? Note { get; set; }
    public string Coupon { get; set; } = "";
    public int Quantity { get; set; }
    public decimal? Discount { get; set; }
    public List<string>? Tags { get; set; }
}

Test data: Id = "A-100", Note = null, Coupon = "", Quantity = 0, Discount = null and Tags an empty list. With default options the real output is:

{"Id":"A-100","Note":null,"Coupon":"","Quantity":0,"Discount":null,"Tags":[]}

Using JsonSerializerOptions at the Method or object level

Create the options once, then pass them to Serialize. Only calls that receive these options are affected.

var ignoreNull = new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

string json = JsonSerializer.Serialize(order, ignoreNull);

Real output: Note and Discount are gone, while the empty string, the zero and the empty list stay:

{"Id":"A-100","Coupon":"","Quantity":0,"Tags":[]}

Reuse one options instance. Creating a new JsonSerializerOptions per call throws away the metadata cache and is slower.

Using JsonSerializerOptions at the Property level

Use the attribute when only some properties should disappear and the rest should be written even when null.

public class Customer
{
    public string Name { get; set; } = "";

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Phone { get; set; }

    public string? Email { get; set; }
}

With Phone and Email both null, the real output keeps Email because only Phone carries the attribute:

{"Name":"Asha","Email":null}

The attribute wins over the global option. With WhenWritingNull set on the options, a property marked [JsonIgnore(Condition = JsonIgnoreCondition.Never)] was still written as "B":null in the test, so you can opt a property back in.

Using JsonSerializerOptions at the global level

In ASP.NET Core the framework serializes responses for you, so set the option where the app is built. In .NET 6 and later with minimal APIs:

builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull);

For controllers, set it on the MVC options. If you use both styles in one app, set both:

builder.Services.AddControllers().AddJsonOptions(o =>
    o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull);

The old Startup.ConfigureServices version of this setting is the same call, services.AddControllers().AddJsonOptions(...). A test web app with both registrations was run, and a minimal API route and a controller were called over HTTP; each returned Person("Asha", null). Both responses were:

{"name":"Asha"}

The property names are camel case because ASP.NET Core uses web defaults. If you want to change that too, see camel case and Pascal case serialization with System.Text.Json.

Ignore empty strings and empty collections

WhenWritingNull keeps "Coupon":"" and "Tags":[], and there is no built-in condition for empty. In .NET 7 and later, a contract customization can set ShouldSerialize per property. This modifier skips empty strings and empty collections and, combined with WhenWritingNull, also nulls:

var ignoreEmpty = new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers =
        {
            ti =>
            {
                foreach (var prop in ti.Properties)
                {
                    if (prop.PropertyType == typeof(string))
                        prop.ShouldSerialize = (_, v) => !string.IsNullOrEmpty((string?)v);
                    else if (typeof(System.Collections.ICollection).IsAssignableFrom(prop.PropertyType))
                        prop.ShouldSerialize = (_, v) => v is System.Collections.ICollection c && c.Count > 0;
                }
            }
        }
    }
};

This needs using System.Text.Json.Serialization.Metadata;. Real output for the test order:

{"Id":"A-100","Quantity":0}

Setting ShouldSerialize replaces the null check for those properties, which is why the nulls are covered by the modifier here as well. Note that WhenWritingDefault is not a shortcut for this: on the test order it removed the null values and the zero, but still wrote "Coupon":"" and "Tags":[] ({"Id":"A-100","Coupon":"","Tags":[]}).

Source generator and other options

If you use the System.Text.Json source generator, put the condition on the context instead of building options:

[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(Order))]
public partial class OrderContext : JsonSerializerContext { }

string json = JsonSerializer.Serialize(order, OrderContext.Default.Order);

The test output was the same as the options example: {"Id":"A-100","Coupon":"","Quantity":0,"Tags":[]}.

Result and common errors

  • ArgumentException when setting the option. DefaultIgnoreCondition = JsonIgnoreCondition.Always throws ArgumentException, as the API reference states. Use WhenWritingNull or WhenWritingDefault. Always only makes sense on a property.
  • Nulls still appear inside a dictionary. In the test, Map = { "k": null } was still written as {"Map":{"k":null}} with WhenWritingNull on. The condition applies to properties, not to dictionary entries. Remove null entries before you serialize, or see serializing dictionaries with System.Text.Json for dictionary handling.
  • Deserialization looks unchanged. The condition only affects writing. Reading {"Id":"B-1"} still leaves Note and Tags as null.
  • The old IgnoreNullValues option. It was the .NET Core 3.x way. It is obsolete; its documentation says it cannot be combined with DefaultIgnoreCondition, so use DefaultIgnoreCondition only.
  • A value of 0 or false disappears. That is WhenWritingDefault doing its job. Switch to WhenWritingNull if a real zero must be kept, and make the property nullable if you need to tell “missing” from “zero”.

If you are mixing Newtonsoft.Json and System.Text.Json in one project, the Newtonsoft equivalent is NullValueHandling.Ignore, which is a different API. For the basics of reading and writing JSON with this library, see serialization and deserialization using System.Text.Json.

What was and was not tested

Tested: every C# snippet above, compiled and run on .NET SDK 10.0.401 (macOS), including the ASP.NET Core minimal API and controller responses over HTTP and the source generator. Not tested: other .NET versions (older versions lack the contract modifier API), Windows, and Native AOT publishing. Results on your own types may differ if you use custom converters, because a converter can change how null is written.

Summary

  • Per call: pass options with DefaultIgnoreCondition = WhenWritingNull.
  • Per property: [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)].
  • Whole app: ConfigureHttpJsonOptions for minimal APIs and AddJsonOptions for controllers.
  • Empty strings and empty lists need a ShouldSerialize modifier (.NET 7+).
  • Dictionary values are not covered by the condition.

Further reading: How to ignore properties with System.Text.Json (Microsoft Learn) and Customize a JSON contract (Microsoft Learn).

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

FAQ

How do I ignore null properties in System.Text.Json?

Set DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull on JsonSerializerOptions and pass the options to JsonSerializer.Serialize. For one property, put [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] on it. In ASP.NET Core, set the same value in ConfigureHttpJsonOptions or AddJsonOptions.

What is the difference between WhenWritingNull and WhenWritingDefault?

WhenWritingNull skips null references and null nullable values. WhenWritingDefault also skips value types that hold their default, such as 0 or false. In the test, an empty string and an empty list were still written under both settings.

How do I ignore empty strings and empty lists as well?

There is no built-in condition. In .NET 7 and later, use a TypeInfoResolver modifier that sets ShouldSerialize on each property to skip empty strings and collections with no items. The example above produced {“Id”:”A-100″,”Quantity”:0} for the test order.

Leave a Reply

Your email address will not be published. Required fields are marked *