diff --git a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj index 64c2c65..bfaa73f 100644 --- a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj +++ b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj @@ -118,6 +118,7 @@ + diff --git a/ICD.Common.Utils/Json/ToStringJsonConverter.cs b/ICD.Common.Utils/Json/ToStringJsonConverter.cs new file mode 100644 index 0000000..ee397fd --- /dev/null +++ b/ICD.Common.Utils/Json/ToStringJsonConverter.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +#if SIMPLSHARP +using Crestron.SimplSharp.Reflection; +#else +using System.Reflection; +#endif +using ICD.Common.Properties; +using Newtonsoft.Json; + +namespace ICD.Common.Utils.Json +{ + /// + /// Simply reads/writes values from/to JSON as their string representation. + /// + [PublicAPI] + public sealed class ToStringJsonConverter : JsonConverter + { + private static readonly Dictionary s_ParseMethods; + + public override bool CanRead { get { return true; } } + + /// + /// Static constructor. + /// + static ToStringJsonConverter() + { + s_ParseMethods = new Dictionary(); + } + + #region Methods + + public override bool CanConvert(Type objectType) + { + return true; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + MethodInfo parse = GetParseMethod(objectType); + if (parse != null) + return parse.Invoke(null, new[] {reader.Value}); + + throw new ArgumentException( + string.Format("{0} does not have a 'static {0} Parse(string)' method.", objectType.Name), + "objectType"); + } + + #endregion + + [CanBeNull] + private static MethodInfo GetParseMethod(Type type) + { + if (type == null) + throw new ArgumentNullException("type"); + + MethodInfo output; + if (!s_ParseMethods.TryGetValue(type, out output)) + { + + output = type +#if SIMPLSHARP + .GetCType() + .GetMethod("Parse", + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, + CType.DefaultBinder, + new CType[] {typeof(string)}, + new ParameterModifier[] {}); +#else + .GetTypeInfo() + .GetMethod("Parse", + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, + Type.DefaultBinder, + new[] {typeof(string)}, + new ParameterModifier[] {}); +#endif + + s_ParseMethods.Add(type, output); + } + + return output; + } + } +}