Files
jsmr/JSMR.Infrastructure/Integrations/DLSite/Serialization/DictionaryConverter.cs
Brian Bicknell a85989a337
Some checks failed
ci / build-test (push) Has been cancelled
ci / publish-image (push) Has been cancelled
Fixed scanning issue. Updated worker.
2026-02-14 22:47:19 -05:00

36 lines
1.3 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
namespace JSMR.Infrastructure.Integrations.DLSite.Serialization;
public sealed class DictionaryConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>> where TKey : notnull
{
public override Dictionary<TKey, TValue>? 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<Dictionary<TKey, TValue>>(ref reader, options) ?? [];
}
throw new JsonException($"Unexpected token {reader.TokenType} when reading Dictionary.");
}
public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, (IDictionary<TKey, TValue>)value, options);
}
}