Deserialize Version type with leading or trailing whitespace

JsonSerializer now throws an exception while deserializing Version types that have leading or trailing whitespace.

Previous behavior

Prior to .NET 7, deserializing Version types that have leading or trailing whitespace was permitted.

New behavior

Started in .NET 7, JsonSerializer throws a FormatException when deserializing Version types that have leading or trailing whitespace.

Version introduced

.NET 7

Type of breaking change

This change can affect binary compatibility.

Reason for change

.NET has optimized the implementation of the underlying Version converter. This resulted in the implementation being made to align with the behavior for other primitive types supported by System.Text.Json, for example, DateTime and Guid, which also disallow leading and trailing spaces.

To get the old behavior back, add a custom converter for the Version type that permits whitespace:

internal sealed class VersionConverter : JsonConverter<Version>
{
    public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string? versionString = reader.GetString();
        if (Version.TryParse(versionString, out Version? result))
        {
            return result;
        }

        ThrowHelper.ThrowJsonException();
        return null;
    }

    public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}

Affected APIs