Spotify.NET/SpotifyAPI.Web/Models/Converters/PlayableItemConverter.cs

52 lines
1.4 KiB
C#
Raw Normal View History

2020-05-01 19:05:28 +01:00
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SpotifyAPI.Web
{
2020-05-07 17:03:20 +01:00
public class PlayableItemConverter : JsonConverter
2020-05-01 19:05:28 +01:00
{
public override bool CanWrite { get => false; }
2020-05-01 19:05:28 +01:00
public override bool CanConvert(Type objectType) => true;
2020-05-25 17:00:38 +01:00
public override object? ReadJson(JsonReader reader, Type objectType,
object? existingValue, JsonSerializer serializer)
2020-05-01 19:05:28 +01:00
{
Ensure.ArgumentNotNull(serializer, nameof(serializer));
2020-05-01 19:05:28 +01:00
var token = JToken.ReadFrom(reader);
if (token.Type == JTokenType.Null)
{
return null;
}
2020-05-25 17:00:38 +01:00
var type = token["type"]?.Value<string>();
2020-05-01 19:05:28 +01:00
if (type == "track")
{
var obj = new FullTrack();
serializer.Populate(token.CreateReader(), obj);
return obj;
}
else if (type == "episode")
{
var obj = new FullEpisode();
serializer.Populate(token.CreateReader(), obj);
return obj;
}
else
{
throw new APIException($@"Received unkown playlist element type: {type}.
If you're requesting a subset of available fields via the fields query paramter,
make sure to include at least the type field. Often it's `items(track(type))` or `item(type)`");
2020-05-01 19:05:28 +01:00
}
}
2020-05-25 17:00:38 +01:00
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
2020-05-01 19:05:28 +01:00
{
throw new NotSupportedException();
}
}
}
2020-05-25 17:00:38 +01:00