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; // validate JSON type if (reader.TokenType != JsonToken.String) throw new SParseException($"Can't parse {nameof(KeybindList)} from {reader.TokenType} node (path: {reader.Path})."); // parse raw value 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)}"); } if (objectType == typeof(KeybindList)) { 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)}"); } throw new SParseException($"Can't parse unexpected type {objectType} from {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()); } /********* ** Private methods *********/ /// Read a JSON string. /// The JSON string value. /// The path to the current JSON node. protected KeybindList ReadString(string str, string path) { 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)}"); } } }