|
| 1 | +--- |
| 2 | +title: "Nullable JsonDocument properties deserialize to JsonValueKind.Null" |
| 3 | +description: Learn about the breaking change in serialization in .NET 9 where nullable JsonDocument values deserialize to JsonValueKind.Null instead of null. |
| 4 | +ms.date: 12/5/2024 |
| 5 | +ai-usage: ai-assisted |
| 6 | +ms.custom: https://github.com/dotnet/docs/issues/43869 |
| 7 | +--- |
| 8 | + |
| 9 | +# Nullable JsonDocument properties deserialize to JsonValueKind.Null |
| 10 | + |
| 11 | +Starting with .NET 9, deserializing `null` JSON values into <xref:System.Text.Json.JsonDocument> results in non-null documents of type <xref:System.Text.Json.JsonValueKind.Null?displayProperty=nameWithType>. |
| 12 | + |
| 13 | +```csharp |
| 14 | +using System.Text.Json; |
| 15 | + |
| 16 | +var doc = JsonSerializer.Deserialize<JsonDocument>("null"); |
| 17 | + |
| 18 | +// Returns true in .NET 8 and false in .NET 9. |
| 19 | +Console.WriteLine(doc is null); |
| 20 | + |
| 21 | +// Returns false in .NET 8 and true in .NET 9. |
| 22 | +Console.WriteLine(doc is { RootElement.ValueKind: JsonValueKind.Null }); |
| 23 | +``` |
| 24 | + |
| 25 | +## Version introduced |
| 26 | + |
| 27 | +.NET 9 |
| 28 | + |
| 29 | +## Previous behavior |
| 30 | + |
| 31 | +In .NET 8 and earlier versions, deserializing `null` JSON values into `JsonDocument` gives back `null` results. |
| 32 | + |
| 33 | +```csharp |
| 34 | +var doc = JsonSerializer.Deserialize<JsonDocument>("null"); |
| 35 | +Console.WriteLine(doc is null); // True. |
| 36 | +``` |
| 37 | + |
| 38 | +## New behavior |
| 39 | + |
| 40 | +Starting in .NET 9, deserializing `null` JSON values into `JsonDocument` gives back non-null instances of `JsonValueKind.Null`. |
| 41 | + |
| 42 | +```csharp |
| 43 | +var doc = JsonSerializer.Deserialize<JsonDocument>("null"); |
| 44 | +Console.WriteLine(doc is null); // False. |
| 45 | +Console.WriteLine(doc is { RootElement.ValueKind: JsonValueKind.Null }); // True. |
| 46 | +``` |
| 47 | + |
| 48 | +## Type of breaking change |
| 49 | + |
| 50 | +This change is a [behavioral change](../../categories.md#behavioral-change). |
| 51 | + |
| 52 | +## Reason for change |
| 53 | + |
| 54 | +This change addresses an inconsistency between root-level JSON nulls and nested nulls in a document. It also makes it consistent with the behavior of the <xref:System.Text.Json.JsonDocument.Parse*?displayProperty=nameWithType> methods. The behavior of returning `null` was considered a bug and updated for alignment with the expected result. |
| 55 | + |
| 56 | +## Recommended action |
| 57 | + |
| 58 | +Update code that consumes deserialized objects containing `JsonDocument` types to expect `JsonValueKind.Null` instead of `null`. |
| 59 | + |
| 60 | +## Affected APIs |
| 61 | + |
| 62 | +* <xref:System.Text.Json.JsonSerializer.Deserialize*?displayProperty=fullName> |
| 63 | +* <xref:System.Text.Json.JsonDocument?displayProperty=fullName> |
0 commit comments