From 41ee8990f81a63c686953b2c28e7af8627fd8098 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 17 Feb 2017 11:33:22 -0500 Subject: write XNA input enums to JSON as strings automatically Mods often reference Json.NET to do this, so this lets many mods remove Json.NET as a dependency. --- .../Serialisation/SelectiveStringEnumConverter.cs | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs (limited to 'src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs') diff --git a/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs b/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs new file mode 100644 index 00000000..e9c5496d --- /dev/null +++ b/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json.Converters; + +namespace StardewModdingAPI.Framework.Serialisation +{ + /// A variant of which only converts certain enums. + internal class SelectiveStringEnumConverter : StringEnumConverter + { + /********* + ** Properties + *********/ + /// The enum type names to convert. + private readonly HashSet Types; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The enum types to convert. + public SelectiveStringEnumConverter(params Type[] types) + { + this.Types = new HashSet(types.Select(p => p.FullName)); + } + + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type type) + { + return base.CanConvert(type) && this.Types.Contains(type.FullName); + } + } +} -- cgit From e321362378eaacd0081db44f0db3ef457ef97368 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 17 Feb 2017 13:59:31 -0500 Subject: fix nullable enums not being written to JSON as string --- .../Framework/Serialisation/SelectiveStringEnumConverter.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs') diff --git a/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs b/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs index e9c5496d..37108556 100644 --- a/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs +++ b/src/StardewModdingAPI/Framework/Serialisation/SelectiveStringEnumConverter.cs @@ -29,7 +29,9 @@ namespace StardewModdingAPI.Framework.Serialisation /// The object type. public override bool CanConvert(Type type) { - return base.CanConvert(type) && this.Types.Contains(type.FullName); + return + base.CanConvert(type) + && this.Types.Contains((Nullable.GetUnderlyingType(type) ?? type).FullName); } } } -- cgit