-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Description
In .NET Core 3.1 and versions 4.6.0-4.7.2 of the System.Text.Json library, null could be passed as the type argument to various serialization methods on JsonSerializer, if the value to serialize was also null. In .NET 5/version 5.0.0, an ArgumentNullException is thrown if null is passed as the type argument.
Version introduced
.NET 5
Old behavior
In .NET Core 3.1 and versions 4.6.0-4.7.2 of the System.Text.Json library, null could be passed as the type argument to various serialization methods on JsonSerializer, if the value to serialize was also null.
New behavior
In .NET 5/version 5.0.0, an ArgumentNullException is thrown if null is passed as the type argument.
Reason for change
null is not expected as a valid input for the type arguments to the various serialization methods. The change was made to ensure correctness and prevent unexpected bugs.
Recommended action
Ensure that a non-null type argument is passed to applicable serialization methods on JsonSerializer. Strategies include handwriting null for values which are null and their type cannot be determined.
For example,
string json;
object? obj = GetObject();
Type? type = obj?.GetType();
if (obj == null)
{
json = "null";
}
else
{
json = JsonSerializer.Serialize(obj, type!);
}Category
- ASP.NET Core
- C#
- Code analysis
- Core .NET libraries
- Cryptography
- Data
- Debugger
- Deployment
- Globalization
- Interop
- JIT
- LINQ
- Managed Extensibility Framework (MEF)
- MSBuild
- Networking
- Printing
- Security
- Serialization
- Visual Basic
- Windows Forms
- Windows Presentation Foundation (WPF)
- XML, XSLT
Affected APIs
- JsonSerializer.Serialize(Object, Type, JsonSerializerOptions)
- JsonSerializer.SerializeToUtf8Bytes(Object, Type, JsonSerializerOptions)
- JsonSerializer.Serialize(Utf8JsonWriter, Object, Type, JsonSerializerOptions)
- JsonSerializer.SerializeAsync(Stream, Object, Type, JsonSerializerOptions, CancellationToken)
Issue metadata
- Issue type: breaking-change