mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-03-26 20:16:33 +00:00
Clean up EnumFlags serialization
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ namespace Jellyfin.Extensions.Json
|
||||
new JsonGuidConverter(),
|
||||
new JsonNullableGuidConverter(),
|
||||
new JsonVersionConverter(),
|
||||
new JsonFlagEnumConverterFactory(),
|
||||
new JsonStringEnumConverter(),
|
||||
new JsonNullableStructConverterFactory(),
|
||||
new JsonBoolNumberConverter(),
|
||||
|
||||
Reference in New Issue
Block a user