using System.Text.Json; using System.Text.Json.Serialization; namespace YandexMusic.API.Models.Landing.Entity.Entities.Context; /// Конвертер для контекста воспроизведения (альбом, исполнитель, плейлист). public class YPlayContextConverter : JsonConverter { public override YPlayContext? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Ожидается объект контекста"); using var doc = JsonDocument.ParseValue(ref reader); var root = doc.RootElement; var contextProp = root.GetProperty("context"); var contextStr = contextProp.GetString(); if (!Enum.TryParse(contextStr, true, out var contextType)) throw new JsonException($"Неизвестный тип контекста: {contextStr}"); var rawText = root.GetRawText(); return contextType switch { YPlayContextType.Album => JsonSerializer.Deserialize(rawText, options), YPlayContextType.Artist => JsonSerializer.Deserialize(rawText, options), YPlayContextType.Playlist => JsonSerializer.Deserialize(rawText, options), _ => JsonSerializer.Deserialize(rawText, options) }; } public override void Write(Utf8JsonWriter writer, YPlayContext value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, options); } }