diff --git a/src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleNull.cs b/src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleNull.cs index 80abfc4a631c..7f7ecb1ef8b0 100644 --- a/src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleNull.cs +++ b/src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleNull.cs @@ -16,8 +16,8 @@ private static bool HandleNull(ref Utf8JsonReader reader, ref ReadStack state, J return false; } - // If we don't have a valid property, that means we read "null" for a root object so just return. - if (state.Current.JsonPropertyInfo == null) + // If null is read at the top level and the type is nullable, then the root is "null" so just return. + if (reader.CurrentDepth == 0 && (state.Current.JsonPropertyInfo == null || state.Current.JsonPropertyInfo.CanBeNull)) { Debug.Assert(state.IsLastFrame); Debug.Assert(state.Current.ReturnValue == null); diff --git a/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs b/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs index c61dab68fb67..73b87ad2e640 100644 --- a/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs +++ b/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests @@ -17,7 +18,7 @@ public static void ClassWithNullProperty() [Fact] public static void RootObjectIsNull() - { + { { TestClassWithNull obj = JsonSerializer.Parse("null"); Assert.Null(obj); @@ -27,6 +28,41 @@ public static void RootObjectIsNull() object obj = JsonSerializer.Parse("null"); Assert.Null(obj); } + + { + string obj = JsonSerializer.Parse("null"); + Assert.Null(obj); + } + + { + IEnumerable obj = JsonSerializer.Parse>("null"); + Assert.Null(obj); + } + + { + Dictionary obj = JsonSerializer.Parse>("null"); + Assert.Null(obj); + } + + } + + [Fact] + public static void RootArrayIsNull() + { + { + int[] obj = JsonSerializer.Parse("null"); + Assert.Null(obj); + } + + { + object[] obj = JsonSerializer.Parse("null"); + Assert.Null(obj); + } + + { + TestClassWithNull[] obj = JsonSerializer.Parse("null"); + Assert.Null(obj); + } } [Fact]