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/macOS 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 {nameof(Vector2)} from invalid value '{str}' (path: {path}).");
float x = Convert.ToSingle(parts[0]);
float y = Convert.ToSingle(parts[1]);
return new Vector2(x, y);
}
}
}