Skip to content

[Breaking change]: JsonSerializer throws FormatException when deserializing Version types with leading or trailing whitespace #26292

Closed
@layomia

Description

@layomia

Description

JsonSerializer goes from permitting leading and trailing whitespace when deserializing Version types to throwing FormatException. Breaking change introduced in .NET 7 Preview 1.

Version

Other (please put exact version in description textbox)

Previous behavior

Provided in description.

New behavior

Provided in description.

Type of breaking change

  • Binary incompatible: Existing binaries may encounter a breaking change in behavior, such as failure to load/execute or different run-time behavior.
  • Source incompatible: Source code may encounter a breaking change in behavior when targeting the new runtime/component/SDK, such as compile errors or different run-time behavior.

Reason for change

We 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 e.g. DateTime and Guid which also disallow leading and trailing spaces.

Recommended action

To get the old behavior back, add a custom converter for the type which 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());
    }
}

Feature area

Core .NET libraries

Affected APIs

All System.Text.Json.JsonSerializer.Deserialize method overloads.

Metadata

Metadata

Assignees

Labels

🏁 Release: .NET 7Work items for the .NET 7 releasebinary incompatibleExisting binaries may encounter a breaking change in behavior.breaking-changeIndicates a .NET Core breaking changesource incompatibleSource code may encounter a breaking change in behavior when targeting the new version.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions