Clean up EnumFlags serialization

This commit is contained in:
Cody Robibero
2022-03-05 13:40:57 -07:00
parent 9ebd521754
commit c331e11c24
9 changed files with 70 additions and 51 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 : Enum
{
private static readonly T[] _enumValues = (T[])Enum.GetValues(typeof(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(),