feat: Standardizing JSON Type conversion

This commit is contained in:
Chris Cameron
2020-06-01 10:27:42 -04:00
parent f53d05936c
commit 28ea05e2f6
4 changed files with 42 additions and 0 deletions

View File

@@ -96,11 +96,15 @@ namespace ICD.Common.Utils.Extensions
/// <param name="extends"></param>
/// <returns></returns>
[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);
}

View File

@@ -132,6 +132,7 @@
<Compile Include="IO\eSeekOrigin.cs" />
<Compile Include="IO\IcdStreamWriter.cs" />
<Compile Include="Json\DateTimeIsoConverter.cs" />
<Compile Include="Json\MinimalTypeConverter.cs" />
<Compile Include="Json\ToStringJsonConverter.cs" />
<Compile Include="NullObject.cs" />
<Compile Include="ProcessorUtils.SimplSharp.cs" />

View File

@@ -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;
}
}

View File

@@ -0,0 +1,34 @@
using System;
using ICD.Common.Utils.Extensions;
using Newtonsoft.Json;
namespace ICD.Common.Utils.Json
{
public sealed class MinimalTypeConverter : AbstractGenericJsonConverter<Type>
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, Type value, JsonSerializer serializer)
{
writer.WriteType(value);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>
/// The object value.
/// </returns>
public override Type ReadJson(JsonReader reader, Type existingValue, JsonSerializer serializer)
{
return reader.GetValueAsType();
}
}
}