using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; namespace Questionable.Model.Common.Converter; public abstract class EnumConverter : JsonConverter where T : Enum { private readonly ReadOnlyDictionary _enumToString; private readonly ReadOnlyDictionary _stringToEnum; protected EnumConverter(IReadOnlyDictionary values) { _enumToString = ((values is IDictionary dictionary) ? new ReadOnlyDictionary(dictionary) : new ReadOnlyDictionary(values.ToDictionary, T, string>((KeyValuePair x) => x.Key, (KeyValuePair x) => x.Value))); _stringToEnum = new ReadOnlyDictionary(_enumToString.ToDictionary, string, T>((KeyValuePair x) => x.Value, (KeyValuePair x) => x.Key)); } public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.String) { throw new JsonException(); } string text = reader.GetString(); if (text == null) { throw new JsonException(); } if (!_stringToEnum.TryGetValue(text, out var value)) { throw new JsonException(); } return value; } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStringValue(_enumToString[value]); } }