using System.Text.Json; using System.Text.Json.Serialization; namespace JSMR.Infrastructure.Integrations.DLSite.Serialization; public sealed class DictionaryConverter : JsonConverter> where TKey : notnull { public override Dictionary? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.StartArray) { if (!reader.Read()) throw new JsonException("Unexpected end while reading array."); if (reader.TokenType != JsonTokenType.EndArray) throw new JsonException("Non-empty JSON array cannot be converted to Dictionary."); return []; } if (reader.TokenType == JsonTokenType.StartObject) { return JsonSerializer.Deserialize>(ref reader, options) ?? []; } throw new JsonException($"Unexpected token {reader.TokenType} when reading Dictionary."); } public override void Write(Utf8JsonWriter writer, Dictionary value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, (IDictionary)value, options); } }