JsonFlagEnumConverter.cs 988 B

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Jellyfin.Extensions.Json.Converters;
  5. /// <summary>
  6. /// Enum flag to json array converter.
  7. /// </summary>
  8. /// <typeparam name="T">The type of enum.</typeparam>
  9. public class JsonFlagEnumConverter<T> : JsonConverter<T>
  10. where T : struct, Enum
  11. {
  12. private static readonly T[] _enumValues = Enum.GetValues<T>();
  13. /// <inheritdoc />
  14. public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. throw new NotImplementedException();
  17. }
  18. /// <inheritdoc />
  19. public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
  20. {
  21. writer.WriteStartArray();
  22. foreach (var enumValue in _enumValues)
  23. {
  24. if (value.HasFlag(enumValue))
  25. {
  26. writer.WriteStringValue(enumValue.ToString());
  27. }
  28. }
  29. writer.WriteEndArray();
  30. }
  31. }