© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
14 replies
possix

deserialize non-nullable

Hello, I want to deserialize JSON with
System.Text.Json.JsonSerializer
System.Text.Json.JsonSerializer
. I have classes with
required
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; }
}
#nullable enable
public class Test
{
    public required string Foo { get; init; }
}


-
{}
{}
is bad json - missing Foo; expected exception
-
{"Foo": 23}
{"Foo": 23}
is bad json - 23 is not a string; expected exception
-
{"Foo": null}
{"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?
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Non-Nullable field (WPF)
C#CC# / help
2y ago
✅ Non-nullable property netstandard2.0
C#CC# / help
13mo ago
Non-Nullable type "required" double up.
C#CC# / help
2y ago
❔ Why does the JsonSerializer.Deserialize return a nullable object
C#CC# / help
3y ago