C#C
C#2y ago
possix

deserialize non-nullable

Hello, I want to deserialize JSON with System.Text.Json.JsonSerializer. I have classes with required properties and it by default throws an exception if any required property is missing, which is nice, I guess. But why doesn't it throw exceptions when I have nullable reference types and the value is null:


#nullable enable
public class Test
{
    public required string Foo { get; init; }
}


  • {}
    is bad json - missing Foo; expected exception
  • {"Foo": 23} is bad json - 23 is not a string; expected exception
  • {"Foo": null} is surprisingly perfectly fine. However, I would expect an exception, because null is not a valid string value in this context (Foo's type is not annotated with ?
    • string?)
Is there any option that I can turn on to throw on null value? I didn't find one.

I think I understand that nullable ? is only for static analysis, but I would still expect different behavior. The deserializer can check with reflection if the ? is there, right? Am I missing something?
Was this page helpful?