Merge pull request #7325 from eyezak/issue/6450

This commit is contained in:
Cody Robibero
2022-03-12 09:08:25 -07:00
committed by GitHub
51 changed files with 5934 additions and 730 deletions

View File

@@ -0,0 +1,36 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Jellyfin.Extensions.Json.Converters;
/// <summary>
/// Enum flag to json array converter.
/// </summary>
/// <typeparam name="T">The type of enum.</typeparam>
public class JsonFlagEnumConverter<T> : JsonConverter<T>
where T : struct, Enum
{
private static readonly T[] _enumValues = Enum.GetValues<T>();
/// <inheritdoc />
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
writer.WriteStartArray();
foreach (var enumValue in _enumValues)
{
if (value.HasFlag(enumValue))
{
writer.WriteStringValue(enumValue.ToString());
}
}
writer.WriteEndArray();
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Jellyfin.Extensions.Json.Converters;
/// <summary>
/// Json flag enum converter factory.
/// </summary>
public class JsonFlagEnumConverterFactory : JsonConverterFactory
{
/// <inheritdoc />
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsEnum && typeToConvert.IsDefined(typeof(FlagsAttribute));
}
/// <inheritdoc />
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
return (JsonConverter?)Activator.CreateInstance(typeof(JsonFlagEnumConverter<>).MakeGenericType(typeToConvert));
}
}

View File

@@ -36,6 +36,7 @@ namespace Jellyfin.Extensions.Json
new JsonGuidConverter(),
new JsonNullableGuidConverter(),
new JsonVersionConverter(),
new JsonFlagEnumConverterFactory(),
new JsonStringEnumConverter(),
new JsonNullableStructConverterFactory(),
new JsonBoolNumberConverter(),