Add JsonConverter for Nullable Guids

pull/4884/head
crobibero 3 years ago
parent 8dfe89ea52
commit cae38f3a7e

@ -0,0 +1,33 @@
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// Converts a GUID object or value to/from JSON.
/// </summary>
public class JsonNullableGuidConverter : JsonConverter<Guid?>
{
/// <inheritdoc />
public override Guid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var guidStr = reader.GetString();
return guidStr == null ? null : new Guid(guidStr);
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options)
{
if (value == null || value == Guid.Empty)
{
writer.WriteNullValue();
}
else
{
writer.WriteStringValue(value.Value.ToString("N", CultureInfo.InvariantCulture));
}
}
}
}

@ -34,6 +34,7 @@ namespace MediaBrowser.Common.Json
Converters =
{
new JsonGuidConverter(),
new JsonNullableGuidConverter(),
new JsonVersionConverter(),
new JsonStringEnumConverter(),
new JsonNullableStructConverterFactory(),

@ -0,0 +1,69 @@
using System;
using System.Globalization;
using System.Text.Json;
using MediaBrowser.Common.Json.Converters;
using Xunit;
namespace Jellyfin.Common.Tests.Json
{
public class JsonNullableGuidConverterTests
{
private readonly JsonSerializerOptions _options;
public JsonNullableGuidConverterTests()
{
_options = new JsonSerializerOptions();
_options.Converters.Add(new JsonNullableGuidConverter());
}
[Fact]
public void Deserialize_Valid_Success()
{
Guid? value = JsonSerializer.Deserialize<Guid?>(@"""a852a27afe324084ae66db579ee3ee18""", _options);
Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value);
}
[Fact]
public void Deserialize_ValidDashed_Success()
{
Guid? value = JsonSerializer.Deserialize<Guid?>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", _options);
Assert.Equal(new Guid("e9b2dcaa-529c-426e-9433-5e9981f27f2e"), value);
}
[Fact]
public void Roundtrip_Valid_Success()
{
Guid guid = new Guid("a852a27afe324084ae66db579ee3ee18");
string value = JsonSerializer.Serialize(guid, _options);
Assert.Equal(guid, JsonSerializer.Deserialize<Guid?>(value, _options));
}
[Fact]
public void Deserialize_Null_EmptyGuid()
{
Assert.Null(JsonSerializer.Deserialize<Guid?>("null", _options));
}
[Fact]
public void Serialize_EmptyGuid_EmptyGuid()
{
Assert.Equal("null", JsonSerializer.Serialize((Guid?)Guid.Empty, _options));
}
[Fact]
public void Serialize_Valid_NoDash_Success()
{
var guid = (Guid?)new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
var str = JsonSerializer.Serialize(guid, _options);
Assert.Equal($"\"{guid:N}\"", str);
}
[Fact]
public void Serialize_Nullable_Success()
{
Guid? guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
var str = JsonSerializer.Serialize(guid, _options);
Assert.Equal($"\"{guid:N}\"", str);
}
}
}
Loading…
Cancel
Save