aboutsummaryrefslogtreecommitdiff
path: root/src/Jellyfin.Extensions/Json/Converters/JsonFlagEnumConverter.cs
blob: 6a0912546ad1d5753f2c18c1388ec9b1c9a120f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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();
    }
}