Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonSerializer.Deserialize on Nullable value types #37913

Closed
amosonn opened this issue Jun 15, 2020 · 1 comment
Closed

JsonSerializer.Deserialize on Nullable value types #37913

amosonn opened this issue Jun 15, 2020 · 1 comment

Comments

@amosonn
Copy link

amosonn commented Jun 15, 2020

Related issues: #434, #1256

System.Text.Json JsonSerializer.DeserializeAsync fails to deserialize Nullable value types. Running:

static void Main(string[] args)
{
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"{ ""SubObj"": {""Field1"": ""value1""}, ""Field2"": ""value2"" }"));
    var des = JsonSerializer.DeserializeAsync<Obj2>(stream).Result;
    System.Console.WriteLine(des.Field2);
    System.Console.WriteLine(des.SubObj.Value.Field1);
}

private struct Obj1
{
    public string? Field1 { get; set; }
}

private class Obj2
{
    public string? Field2 { get; set; }
    public Obj1? SubObj { get; set; }
}

Prints:

value2
Unhandled exception. System.InvalidOperationException: Nullable object must have a value.
   at System.Nullable`1.get_Value()
   at test_deser.Program.Main(String[] args) in /tmp/test_deser/Program.cs:line 15

Removing the ? and the Value works as expected:

-    System.Console.WriteLine(des.SubObj.Value.Field1);
+    System.Console.WriteLine(des.SubObj.Field1);

-    public Obj1? SubObj { get; set; }
+    public Obj1 SubObj { get; set; }

Prints:

value2
value1

On netcore 3.1.3. Using nullable types syntax, but this displays the same behavior with explicit Nullable<Obj1>.

@Dotnet-GitSync-Bot Dotnet-GitSync-Bot added area-System.Text.Json untriaged New issue has not been triaged by the area owner labels Jun 15, 2020
@layomia layomia added this to the 5.0.0 milestone Jun 30, 2020
@layomia layomia removed the untriaged New issue has not been triaged by the area owner label Jun 30, 2020
@layomia
Copy link
Contributor

layomia commented Jun 30, 2020

This is fixed in 5.0, following #2259. However, porting the fix to 3.x will not meet the servicing bar.

Some workarounds here are to use a custom converter, upgrade the app to a preview of .NET 5, or use a preview of the System.Text.Json v5.0.0 package on NuGet.

@layomia layomia closed this as completed Jun 30, 2020
@ghost ghost locked as resolved and limited conversation to collaborators Dec 8, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants