A System.Text.Json converter that reads a JSON object mapping Lichess gamemode names to stats and returns a Dictionary<Gamemode, IGameStats>. It parses each property name into a Gamemode and deserializes the value into either GamemodeStats (if it has a "games" property) or RunStats (if it has a "runs" property).
#nullable enable annotations
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using LichessNET.Entities.Enumerations;
using LichessNET.Entities.Game;
using LichessNET.Entities.Interfaces;
using LichessNET.Entities.Stats;
namespace LichessNET.Converters;
public class GameStatsConverter : JsonConverter<Dictionary<Gamemode, IGameStats>>
{
public override Dictionary<Gamemode, IGameStats>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var output = new Dictionary<Gamemode, IGameStats>();
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
foreach (JsonProperty property in doc.RootElement.EnumerateObject())
{
if (Gamemode.TryParse(property.Name, true, out Gamemode gamemode))
{
IGameStats? stats = null;
if (property.Value.TryGetProperty("games", out _))
{
stats = JsonSerializer.Deserialize<GamemodeStats>(property.Value, new JsonSerializerOptions(){PropertyNameCaseInsensitive = true});
}
else if (property.Value.TryGetProperty("runs", out _))
{
stats = JsonSerializer.Deserialize<RunStats>(property.Value, new JsonSerializerOptions(){PropertyNameCaseInsensitive = true});
}
if (stats != null)
{
output.Add(gamemode, stats);
}
}
}
}
return output;
}
public override void Write(Utf8JsonWriter writer, Dictionary<Gamemode, IGameStats> value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}