From 9636d5b3aac99459e5933bc4fa6ddb8ca84917af Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 20 Jan 2018 21:26:21 -0500 Subject: [PATCH] encapsulate common JSON converter code, improve parse errors (#423) --- docs/release-notes.md | 1 + .../Framework/Serialisation/ColorConverter.cs | 90 ++++++------------ .../Framework/Serialisation/JsonHelper.cs | 13 ++- .../Framework/Serialisation/PointConverter.cs | 83 +++++------------ .../Serialisation/RectangleConverter.cs | 91 ++++++------------- .../Serialisation/SimpleReadOnlyConverter.cs | 77 ++++++++++++++++ src/SMAPI/StardewModdingAPI.csproj | 1 + 7 files changed, 167 insertions(+), 189 deletions(-) create mode 100644 src/SMAPI/Framework/Serialisation/SimpleReadOnlyConverter.cs diff --git a/docs/release-notes.md b/docs/release-notes.md index 27110bff..31ceb7de 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -12,6 +12,7 @@ * For modders: * Added `SButton` `IsActionButton()` and `IsUseToolButton()` extensions. + * Improved JSON parse errors to provide more useful info for troubleshooting. * Fixed events being raised while the game is loading a save file. * Fixed input events not recognising controller input as an action or use-tool button. * Fixed input events setting the same `IsActionButton` and `IsUseToolButton` values for all buttons pressed in an update tick. diff --git a/src/SMAPI/Framework/Serialisation/ColorConverter.cs b/src/SMAPI/Framework/Serialisation/ColorConverter.cs index d29f73b8..d2315a00 100644 --- a/src/SMAPI/Framework/Serialisation/ColorConverter.cs +++ b/src/SMAPI/Framework/Serialisation/ColorConverter.cs @@ -1,82 +1,46 @@ using System; using Microsoft.Xna.Framework; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using StardewModdingAPI.Framework.Exceptions; namespace StardewModdingAPI.Framework.Serialisation { /// Handles deserialisation of for crossplatform compatibility. - internal class ColorConverter : JsonConverter + /// + /// - Linux/Mac format: { "B": 76, "G": 51, "R": 25, "A": 102 } + /// - Windows format: "26, 51, 76, 102" + /// + internal class ColorConverter : SimpleReadOnlyConverter { /********* - ** Accessors + ** Protected methods *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Color ReadObject(JObject obj, string path) { - return objectType == typeof(Color); + int r = obj.Value(nameof(Color.R)); + int g = obj.Value(nameof(Color.G)); + int b = obj.Value(nameof(Color.B)); + int a = obj.Value(nameof(Color.A)); + return new Color(r, g, b, a); } - /// 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) + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Color ReadString(string str, string path) { - // Linux/Mac: { "B": 76, "G": 51, "R": 25, "A": 102 } - // Windows: "26, 51, 76, 102" - JToken token = JToken.Load(reader); - switch (token.Type) - { - case JTokenType.Object: - { - JObject obj = (JObject)token; - int r = obj.Value(nameof(Color.R)); - int g = obj.Value(nameof(Color.G)); - int b = obj.Value(nameof(Color.B)); - int a = obj.Value(nameof(Color.A)); - return new Color(r, g, b, a); - } + string[] parts = str.Split(','); + if (parts.Length != 4) + throw new SParseException($"Can't parse {typeof(Color).Name} from invalid value '{str}' (path: {path})."); - case JTokenType.String: - { - string str = token.Value(); - if (string.IsNullOrWhiteSpace(str)) - return null; - - string[] parts = str.Split(','); - if (parts.Length != 4) - throw new SParseException($"Can't parse {typeof(Color).Name} from {token.Path}, invalid value '{str}'."); - - int r = Convert.ToInt32(parts[0]); - int g = Convert.ToInt32(parts[1]); - int b = Convert.ToInt32(parts[2]); - int a = Convert.ToInt32(parts[3]); - return new Color(r, g, b, a); - } - - default: - throw new SParseException($"Can't parse {typeof(Point).Name} from {token.Path}, must be an object or string."); - } - } - - /// 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) - { - throw new InvalidOperationException("This converter does not write JSON."); + int r = Convert.ToInt32(parts[0]); + int g = Convert.ToInt32(parts[1]); + int b = Convert.ToInt32(parts[2]); + int a = Convert.ToInt32(parts[3]); + return new Color(r, g, b, a); } } } diff --git a/src/SMAPI/Framework/Serialisation/JsonHelper.cs b/src/SMAPI/Framework/Serialisation/JsonHelper.cs index f66f9dfb..90a6d258 100644 --- a/src/SMAPI/Framework/Serialisation/JsonHelper.cs +++ b/src/SMAPI/Framework/Serialisation/JsonHelper.cs @@ -63,11 +63,16 @@ namespace StardewModdingAPI.Framework.Serialisation { return this.Deserialise(json); } - catch (JsonReaderException ex) + catch (Exception ex) { - string error = $"The file at {fullPath} doesn't seem to be valid JSON."; - if (json.Contains("“") || json.Contains("”")) - error += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; + string error = $"Can't parse JSON file at {fullPath}."; + + if (ex is JsonReaderException) + { + error += " This doesn't seem to be valid JSON."; + if (json.Contains("“") || json.Contains("”")) + error += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; + } error += $"\nTechnical details: {ex.Message}"; throw new JsonReaderException(error); } diff --git a/src/SMAPI/Framework/Serialisation/PointConverter.cs b/src/SMAPI/Framework/Serialisation/PointConverter.cs index d35660be..bdcefaa5 100644 --- a/src/SMAPI/Framework/Serialisation/PointConverter.cs +++ b/src/SMAPI/Framework/Serialisation/PointConverter.cs @@ -1,79 +1,42 @@ using System; using Microsoft.Xna.Framework; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using StardewModdingAPI.Framework.Exceptions; namespace StardewModdingAPI.Framework.Serialisation { /// Handles deserialisation of for crossplatform compatibility. - internal class PointConverter : JsonConverter + /// + /// - Linux/Mac format: { "X": 1, "Y": 2 } + /// - Windows format: "1, 2" + /// + internal class PointConverter : SimpleReadOnlyConverter { /********* - ** Accessors + ** Protected methods *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Point ReadObject(JObject obj, string path) { - return objectType == typeof(Point); + int x = obj.Value(nameof(Point.X)); + int y = obj.Value(nameof(Point.Y)); + return new Point(x, y); } - /// 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) + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Point ReadString(string str, string path) { - // point - // Linux/Mac: { "X": 1, "Y": 2 } - // Windows: "1, 2" - JToken token = JToken.Load(reader); - switch (token.Type) - { - case JTokenType.Object: - { - JObject obj = (JObject)token; - int x = obj.Value(nameof(Point.X)); - int y = obj.Value(nameof(Point.Y)); - return new Point(x, y); - } + string[] parts = str.Split(','); + if (parts.Length != 2) + throw new SParseException($"Can't parse {typeof(Point).Name} from invalid value '{str}' (path: {path})."); - case JTokenType.String: - { - string str = token.Value(); - if (string.IsNullOrWhiteSpace(str)) - return null; - - string[] parts = str.Split(','); - if (parts.Length != 2) - throw new SParseException($"Can't parse {typeof(Point).Name} from {token.Path}, invalid value '{str}'."); - - int x = Convert.ToInt32(parts[0]); - int y = Convert.ToInt32(parts[1]); - return new Point(x, y); - } - - default: - throw new SParseException($"Can't parse {typeof(Point).Name} from {token.Path}, must be an object or string."); - } - } - - /// 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) - { - throw new InvalidOperationException("This converter does not write JSON."); + int x = Convert.ToInt32(parts[0]); + int y = Convert.ToInt32(parts[1]); + return new Point(x, y); } } } diff --git a/src/SMAPI/Framework/Serialisation/RectangleConverter.cs b/src/SMAPI/Framework/Serialisation/RectangleConverter.cs index 74df54e2..bbf60435 100644 --- a/src/SMAPI/Framework/Serialisation/RectangleConverter.cs +++ b/src/SMAPI/Framework/Serialisation/RectangleConverter.cs @@ -1,84 +1,51 @@ using System; using System.Text.RegularExpressions; using Microsoft.Xna.Framework; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using StardewModdingAPI.Framework.Exceptions; namespace StardewModdingAPI.Framework.Serialisation { /// Handles deserialisation of for crossplatform compatibility. - internal class RectangleConverter : JsonConverter + /// + /// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 } + /// - Windows format: "{X:1 Y:2 Width:3 Height:4}" + /// + internal class RectangleConverter : SimpleReadOnlyConverter { /********* - ** Accessors + ** Protected methods *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Rectangle ReadObject(JObject obj, string path) { - return objectType == typeof(Rectangle); + int x = obj.Value(nameof(Rectangle.X)); + int y = obj.Value(nameof(Rectangle.Y)); + int width = obj.Value(nameof(Rectangle.Width)); + int height = obj.Value(nameof(Rectangle.Height)); + return new Rectangle(x, y, width, height); } - /// 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) + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Rectangle ReadString(string str, string path) { - // Linux/Mac: { "X": 1, "Y": 2, "Width": 3, "Height": 4 } - // Windows: "{X:1 Y:2 Width:3 Height:4}" - JToken token = JToken.Load(reader); - switch (token.Type) - { - case JTokenType.Object: - { - JObject obj = (JObject)token; - int x = obj.Value(nameof(Rectangle.X)); - int y = obj.Value(nameof(Rectangle.Y)); - int width = obj.Value(nameof(Rectangle.Width)); - int height = obj.Value(nameof(Rectangle.Height)); - return new Rectangle(x, y, width, height); - } + if (string.IsNullOrWhiteSpace(str)) + return Rectangle.Empty; - case JTokenType.String: - { - string str = token.Value(); - if (string.IsNullOrWhiteSpace(str)) - return Rectangle.Empty; + var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$"); + if (!match.Success) + throw new SParseException($"Can't parse {typeof(Rectangle).Name} from invalid value '{str}' (path: {path})."); - var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$"); - if (!match.Success) - throw new SParseException($"Can't parse {typeof(Rectangle).Name} from {reader.Path}, invalid string format."); + int x = Convert.ToInt32(match.Groups["x"].Value); + int y = Convert.ToInt32(match.Groups["y"].Value); + int width = Convert.ToInt32(match.Groups["width"].Value); + int height = Convert.ToInt32(match.Groups["height"].Value); - int x = Convert.ToInt32(match.Groups["x"].Value); - int y = Convert.ToInt32(match.Groups["y"].Value); - int width = Convert.ToInt32(match.Groups["width"].Value); - int height = Convert.ToInt32(match.Groups["height"].Value); - - return new Rectangle(x, y, width, height); - } - - default: - throw new SParseException($"Can't parse {typeof(Rectangle).Name} from {reader.Path}, must be an object or string."); - } - } - - /// 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) - { - throw new InvalidOperationException("This converter does not write JSON."); + return new Rectangle(x, y, width, height); } } } diff --git a/src/SMAPI/Framework/Serialisation/SimpleReadOnlyConverter.cs b/src/SMAPI/Framework/Serialisation/SimpleReadOnlyConverter.cs new file mode 100644 index 00000000..9308456b --- /dev/null +++ b/src/SMAPI/Framework/Serialisation/SimpleReadOnlyConverter.cs @@ -0,0 +1,77 @@ +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Framework.Exceptions; + +namespace StardewModdingAPI.Framework.Serialisation +{ + /// The base implementation for simplified converters which deserialise without overriding serialisation. + /// The type to deserialise. + internal abstract class SimpleReadOnlyConverter : JsonConverter + { + /********* + ** Accessors + *********/ + /// Whether this converter can write JSON. + public override bool CanWrite => false; + + + /********* + ** Public methods + *********/ + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type objectType) + { + return objectType == typeof(T); + } + + /// 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) + { + throw new InvalidOperationException("This converter does not write JSON."); + } + + /// 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.StartObject: + return this.ReadObject(JObject.Load(reader), path); + case JsonToken.String: + return this.ReadString(JToken.Load(reader).Value(), path); + default: + throw new SParseException($"Can't parse {typeof(T).Name} from {reader.TokenType} (path: {reader.Path})."); + } + } + + + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected virtual T ReadObject(JObject obj, string path) + { + throw new SParseException($"Can't parse {typeof(T).Name} from object (path: {path})."); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected virtual T ReadString(string str, string path) + { + throw new SParseException($"Can't parse {typeof(T).Name} from string (path: {path})."); + } + } +} diff --git a/src/SMAPI/StardewModdingAPI.csproj b/src/SMAPI/StardewModdingAPI.csproj index e02e1ab4..dd4f6134 100644 --- a/src/SMAPI/StardewModdingAPI.csproj +++ b/src/SMAPI/StardewModdingAPI.csproj @@ -110,6 +110,7 @@ +