using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StardewModdingAPI.Toolkit.Serialization;
using StardewModdingAPI.Utilities;
namespace StardewModdingAPI.Framework.Serialization
{
/// Handles deserialization of and models.
internal class KeybindConverter : JsonConverter
{
/*********
** Accessors
*********/
///
public override bool CanRead { get; } = true;
///
public override bool CanWrite { get; } = true;
/*********
** Public methods
*********/
/// Get whether this instance can convert the specified object type.
/// The object type.
public override bool CanConvert(Type objectType)
{
return
typeof(Keybind).IsAssignableFrom(objectType)
|| typeof(KeybindList).IsAssignableFrom(objectType);
}
/// Reads the JSON representation of the object.
/// The JSON reader.
/// The object type.
/// The object being read.
/// The calling serializer.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string path = reader.Path;
switch (reader.TokenType)
{
case JsonToken.Null:
return objectType == typeof(Keybind)
? (object)new Keybind()
: new KeybindList();
case JsonToken.String:
{
string str = JToken.Load(reader).Value();
if (objectType == typeof(Keybind))
{
return Keybind.TryParse(str, out Keybind parsed, out string[] errors)
? parsed
: throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
else
{
return KeybindList.TryParse(str, out KeybindList parsed, out string[] errors)
? parsed
: throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
}
default:
throw new SParseException($"Can't parse {objectType} from unexpected {reader.TokenType} node (path: {reader.Path}).");
}
}
/// Writes the JSON representation of the object.
/// The JSON writer.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value?.ToString());
}
}
}