From 28ea05e2f616649944ab7f427cb554f5b21cbd1b Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Mon, 1 Jun 2020 10:27:42 -0400 Subject: [PATCH] feat: Standardizing JSON Type conversion --- .../Extensions/JsonReaderExtensions.cs | 4 +++ .../ICD.Common.Utils_SimplSharp.csproj | 1 + ICD.Common.Utils/Json/JsonUtils.cs | 3 ++ ICD.Common.Utils/Json/MinimalTypeConverter.cs | 34 +++++++++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 ICD.Common.Utils/Json/MinimalTypeConverter.cs diff --git a/ICD.Common.Utils/Extensions/JsonReaderExtensions.cs b/ICD.Common.Utils/Extensions/JsonReaderExtensions.cs index 375cdac..f99299e 100644 --- a/ICD.Common.Utils/Extensions/JsonReaderExtensions.cs +++ b/ICD.Common.Utils/Extensions/JsonReaderExtensions.cs @@ -96,11 +96,15 @@ namespace ICD.Common.Utils.Extensions /// /// [PublicAPI] + [CanBeNull] public static Type GetValueAsType([NotNull] this JsonReader extends) { if (extends == null) throw new ArgumentNullException("extends"); + if (extends.TokenType == JsonToken.Null) + return null; + string value = extends.GetValueAsString(); return Type.GetType(value); } diff --git a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj index abb9f32..0baaf3b 100644 --- a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj +++ b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj @@ -132,6 +132,7 @@ + diff --git a/ICD.Common.Utils/Json/JsonUtils.cs b/ICD.Common.Utils/Json/JsonUtils.cs index 5528e3e..e48068b 100644 --- a/ICD.Common.Utils/Json/JsonUtils.cs +++ b/ICD.Common.Utils/Json/JsonUtils.cs @@ -40,6 +40,9 @@ namespace ICD.Common.Utils.Json // Serialize DateTimes to ISO s_CommonSettings.Converters.Add(new DateTimeIsoConverter()); + // Minify Type serialization + s_CommonSettings.Converters.Add(new MinimalTypeConverter()); + return s_CommonSettings; } } diff --git a/ICD.Common.Utils/Json/MinimalTypeConverter.cs b/ICD.Common.Utils/Json/MinimalTypeConverter.cs new file mode 100644 index 0000000..e11c1b0 --- /dev/null +++ b/ICD.Common.Utils/Json/MinimalTypeConverter.cs @@ -0,0 +1,34 @@ +using System; +using ICD.Common.Utils.Extensions; +using Newtonsoft.Json; + +namespace ICD.Common.Utils.Json +{ + public sealed class MinimalTypeConverter : AbstractGenericJsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, Type value, JsonSerializer serializer) + { + writer.WriteType(value); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// The existing value of object being read. + /// The calling serializer. + /// + /// The object value. + /// + public override Type ReadJson(JsonReader reader, Type existingValue, JsonSerializer serializer) + { + return reader.GetValueAsType(); + } + } +}