diff --git a/src/Snap.Tests/Core/Json/SemanticVersionSystemTextJsonConverterTests.cs b/src/Snap.Tests/Core/Json/SemanticVersionSystemTextJsonConverterTests.cs new file mode 100644 index 00000000..54cfc6f9 --- /dev/null +++ b/src/Snap.Tests/Core/Json/SemanticVersionSystemTextJsonConverterTests.cs @@ -0,0 +1,30 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using NuGet.Versioning; +using Snap.Core.Json; +using Xunit; + +namespace Snap.Tests.Core.Json; + +file sealed class SemanticVersionDto +{ + [JsonInclude, JsonConverter(typeof(SemanticVersionSystemTextJsonConverter))] + public SemanticVersion Value { get; init; } +} + +public sealed class SemanticVersionSystemTextJsonConverterTests +{ + [Fact] + public void TestSerializeDeserialize() + { + var dto = new SemanticVersionDto + { + Value = new SemanticVersion(1, 0, 0, "abc", "metadata") + }; + + var json = JsonSerializer.Serialize(dto); + var deserializedDto = JsonSerializer.Deserialize(json); + Assert.NotNull(deserializedDto); + Assert.Equal(dto.Value, deserializedDto.Value); + } +} diff --git a/src/Snap/Core/Json/SemanticVersionSystemTextJsonConverter.cs b/src/Snap/Core/Json/SemanticVersionSystemTextJsonConverter.cs new file mode 100644 index 00000000..b2c39b36 --- /dev/null +++ b/src/Snap/Core/Json/SemanticVersionSystemTextJsonConverter.cs @@ -0,0 +1,23 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; +using NuGet.Versioning; + +namespace Snap.Core.Json; + +public sealed class SemanticVersionSystemTextJsonConverter : JsonConverter +{ + public override SemanticVersion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + if (string.IsNullOrEmpty(value)) + { + return null; + } + _ = SemanticVersion.TryParse(value, out var semanticVersion); + return semanticVersion; + } + + public override void Write(Utf8JsonWriter writer, SemanticVersion value, JsonSerializerOptions options) => + writer.WriteStringValue(value.ToString()); +} diff --git a/src/Snap/Core/SnapNugetService.cs b/src/Snap/Core/SnapNugetService.cs index 2c3a8109..d6175a0b 100644 --- a/src/Snap/Core/SnapNugetService.cs +++ b/src/Snap/Core/SnapNugetService.cs @@ -11,6 +11,7 @@ using NuGet.Versioning; using SharpCompress.Readers; using Snap.AnyOS; +using Snap.Core.Json; using Snap.Core.Models; using Snap.Extensions; using Snap.Logging; @@ -20,7 +21,7 @@ namespace Snap.Core; public sealed record SnapReleaseDetails { - [JsonInclude] + [JsonInclude, JsonConverter(typeof(SemanticVersionSystemTextJsonConverter))] public SemanticVersion Version { get; init; } [JsonInclude] public string Channel { get; init; }