|
| 1 | +--- |
| 2 | +title: "Breaking change: Deserialize Version with leading/trailing whitespace" |
| 3 | +description: Learn about the .NET 7 breaking change for deserializing Version types with leading or trailing whitespace. |
| 4 | +ms.date: 01/11/2022 |
| 5 | +--- |
| 6 | +# Deserialize Version type with leading or trailing whitespace |
| 7 | + |
| 8 | +<xref:System.Text.Json.JsonSerializer> now throws an exception while deserializing <xref:System.Version> types that have leading or trailing whitespace. |
| 9 | + |
| 10 | +## Previous behavior |
| 11 | + |
| 12 | +Prior to .NET 7, deserializing <xref:System.Version> types that have leading or trailing whitespace was permitted. |
| 13 | + |
| 14 | +## New behavior |
| 15 | + |
| 16 | +Started in .NET 7, <xref:System.Text.Json.JsonSerializer> throws a <xref:System.FormatException> when deserializing <xref:System.Version> types that have leading or trailing whitespace. |
| 17 | + |
| 18 | +## Version introduced |
| 19 | + |
| 20 | +.NET 7 Preview 1 |
| 21 | + |
| 22 | +## Type of breaking change |
| 23 | + |
| 24 | +This change can affect [binary compatibility](../../categories.md#binary-compatibility). |
| 25 | + |
| 26 | +## Reason for change |
| 27 | + |
| 28 | +.NET has optimized the implementation of the underlying <xref:System.Version> converter. This resulted in the implementation being made to align with the behavior for other primitive types supported by <xref:System.Text.Json?displayProperty=fullName>, for example, <xref:System.DateTime> and <xref:System.Guid>, which also disallow leading and trailing spaces. |
| 29 | + |
| 30 | +## Recommended action |
| 31 | + |
| 32 | +To get the old behavior back, add a custom converter for the <xref:System.Version> type that permits whitespace: |
| 33 | + |
| 34 | +```csharp |
| 35 | +internal sealed class VersionConverter : JsonConverter<Version> |
| 36 | +{ |
| 37 | + public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 38 | + { |
| 39 | + string? versionString = reader.GetString(); |
| 40 | + if (Version.TryParse(versionString, out Version? result)) |
| 41 | + { |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + ThrowHelper.ThrowJsonException(); |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) |
| 50 | + { |
| 51 | + writer.WriteStringValue(value.ToString()); |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +## Affected APIs |
| 57 | + |
| 58 | +- <xref:System.Text.Json.JsonSerializer.Deserialize%2A?displayProperty=fullName> |
| 59 | +- <xref:System.Text.Json.JsonSerializer.DeserializeAsync%2A?displayProperty=fullName> |
0 commit comments