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.

Make sure that you are not passing null for the Type inputType parameter of these methods.

Affected APIs