Skip to content

Commit

Permalink
Add semantic version system.text.json converter.
Browse files Browse the repository at this point in the history
  • Loading branch information
peters committed Mar 1, 2024
1 parent 48c3ccc commit 60ce9d3
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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<SemanticVersionDto>(json);
Assert.NotNull(deserializedDto);
Assert.Equal(dto.Value, deserializedDto.Value);
}
}
23 changes: 23 additions & 0 deletions src/Snap/Core/Json/SemanticVersionSystemTextJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -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<SemanticVersion>
{
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());
}
3 changes: 2 additions & 1 deletion src/Snap/Core/SnapNugetService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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; }
Expand Down

0 comments on commit 60ce9d3

Please sign in to comment.