JsonNumberHandlingAttribute on collection properties

A minor breaking change was introduced in .NET 6 with regard to the JsonNumberHandlingAttribute attribute. If you apply the attribute to a property that's a collection of non-number values and attempt to serialize or deserialize the property, an InvalidOperationException is thrown. The attribute is only valid for properties that are collections of number types, for example:

[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)]
public List<int> MyList { get; set; }

Previous behavior

Although it was ignored during serialization, JsonNumberHandlingAttribute could be applied to properties that were collections of non-number types. For example:

[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)]
public List<MyClass> MyList { get; set; }

New behavior

Starting in .NET 6, if you apply JsonNumberHandlingAttribute to a property that's a collection of non-number values and attempt to serialize or deserialize the property, an InvalidOperationException is thrown.

Version introduced

.NET 6

Type of breaking change

This change can affect binary compatibility.

Reason for change

This change was a side effect of a performance optimization for the number handling feature.

Remove the JsonNumberHandlingAttribute attribute from incompatible collection properties.

Affected APIs

All of the System.Text.Json.JsonSerializer serialization and deserialization methods.