JsonSerializer.Serialize throws ArgumentNullException when type parameter is null
JsonSerializer.Serialize, JsonSerializer.SerializeAsync, and JsonSerializer.SerializeToUtf8Bytes overloads that have a parameter of type Type now throw an ArgumentNullException whenever null
is passed for that parameter.
Change description
In .NET Core 3.1, the JsonSerializer.Serialize, JsonSerializer.SerializeAsync(Stream, Object, Type, JsonSerializerOptions, CancellationToken), and JsonSerializer.SerializeToUtf8Bytes(Object, Type, JsonSerializerOptions) overloads that have a Type parameter throw an ArgumentNullException when null
is passed for the Type inputType
parameter, but not if the Object value
parameter is also null
. Starting in .NET 5, these methods always throw an ArgumentNullException when null
is passed for the Type parameter.
Behavior in .NET Core 3.1:
// Returns a string with value "null".
JsonSerializer.Serialize(null, null);
// Returns a byte array with value "null".
JsonSerializer.SerializeToUtf8Bytes(null, null);
Behavior in .NET 5 and later:
// Throws ArgumentNullException: "Value cannot be null. (Parameter 'inputType')".
JsonSerializer.Serialize(null, null);
// Throws ArgumentNullException: "Value cannot be null. (Parameter 'inputType')".
JsonSerializer.SerializeToUtf8Bytes(null, null);
Version introduced
5.0
Reason for change
Passing in null
for the Type inputType
parameter is unacceptable and should always throw an ArgumentNullException.
Recommended action
Make sure that you are not passing null
for the Type inputType
parameter of these methods.
Affected APIs
- System.Text.Json.JsonSerializer.Serialize(Object, Type, JsonSerializerOptions)
- System.Text.Json.JsonSerializer.Serialize(Utf8JsonWriter, Object, Type, JsonSerializerOptions)
- System.Text.Json.JsonSerializer.SerializeAsync(Stream, Object, Type, JsonSerializerOptions, CancellationToken)
- System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(Object, Type, JsonSerializerOptions)
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for