From 70a1334f2c50cff279344b9b9d52d71c847516a7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 1 Feb 2020 01:08:29 -0500 Subject: add JSON converter for Vector2 --- .../Framework/Serialization/PointConverter.cs | 2 +- .../Framework/Serialization/Vector2Converter.cs | 43 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/SMAPI/Framework/Serialization/Vector2Converter.cs (limited to 'src/SMAPI/Framework/Serialization') diff --git a/src/SMAPI/Framework/Serialization/PointConverter.cs b/src/SMAPI/Framework/Serialization/PointConverter.cs index 8c2f3396..3481c9b2 100644 --- a/src/SMAPI/Framework/Serialization/PointConverter.cs +++ b/src/SMAPI/Framework/Serialization/PointConverter.cs @@ -6,7 +6,7 @@ using StardewModdingAPI.Toolkit.Serialization.Converters; namespace StardewModdingAPI.Framework.Serialization { - /// Handles deserialization of for crossplatform compatibility. + /// Handles deserialization of for crossplatform compatibility. /// /// - Linux/Mac format: { "X": 1, "Y": 2 } /// - Windows format: "1, 2" diff --git a/src/SMAPI/Framework/Serialization/Vector2Converter.cs b/src/SMAPI/Framework/Serialization/Vector2Converter.cs new file mode 100644 index 00000000..1d9b08e0 --- /dev/null +++ b/src/SMAPI/Framework/Serialization/Vector2Converter.cs @@ -0,0 +1,43 @@ +using System; +using Microsoft.Xna.Framework; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Framework.Serialization +{ + /// Handles deserialization of for crossplatform compatibility. + /// + /// - Linux/Mac format: { "X": 1, "Y": 2 } + /// - Windows format: "1, 2" + /// + internal class Vector2Converter : SimpleReadOnlyConverter + { + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Vector2 ReadObject(JObject obj, string path) + { + float x = obj.ValueIgnoreCase(nameof(Vector2.X)); + float y = obj.ValueIgnoreCase(nameof(Vector2.Y)); + return new Vector2(x, y); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Vector2 ReadString(string str, string path) + { + string[] parts = str.Split(','); + if (parts.Length != 2) + throw new SParseException($"Can't parse {typeof(Vector2).Name} from invalid value '{str}' (path: {path})."); + + float x = Convert.ToSingle(parts[0]); + float y = Convert.ToSingle(parts[1]); + return new Vector2(x, y); + } + } +} -- cgit