Skip to content

JsonIgnoreCondition.WhenWritingNull doesn't play well with required nullable properties #76527

@asleire

Description

@asleire

.NET SDK: 7.0.100-rc.1.22431.12

I'm not sure if this is intentional or not, but I'm experiencing an issue when trying to use required nullable properties in my API DTOs.

  1. I want to mark my properties as required in order to force my code to initialize all the properties, even the properties that are nullable.
  2. I want to serialize my objects with the serializer option DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull.

Combining these points lead to an exception upon deserializing a serialized object whose nullable required property was set to null.

I would expect deserialization to ignore required nullable properties when DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull

Minimal reproduction

Code:

using System.Text.Json;
using System.Text.Json.Serialization;

var jsonSerializerOptions = new JsonSerializerOptions()
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};

var serializedFoo = JsonSerializer.Serialize(new Foo() { Bar = null }, jsonSerializerOptions);

// This line throws an exception: JSON deserialization for type 'Foo' was missing required properties, including the following: Bar
JsonSerializer.Deserialize<Foo>(serializedFoo, jsonSerializerOptions);

public class Foo
{
    public required string? Bar { get; set; }
}

Exception:

Unhandled exception. System.Text.Json.JsonException: JSON deserialization for type 'Foo' was missing required properties, including the following: Bar
   at System.Text.Json.ThrowHelper.ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions