-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
area-System.Text.JsonquestionAnswer questions and provide assistance, not an issue with source code or documentation.Answer questions and provide assistance, not an issue with source code or documentation.
Milestone
Description
.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.
- 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.
- 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)
pinkfloydx33
Metadata
Metadata
Assignees
Labels
area-System.Text.JsonquestionAnswer questions and provide assistance, not an issue with source code or documentation.Answer questions and provide assistance, not an issue with source code or documentation.