fix: Throwing an exception when trying to read non-primitive JSON tokens as string

This commit is contained in:
Chris Cameron
2019-07-01 17:07:50 -04:00
parent 3d068aeb68
commit 909ebfbc97
3 changed files with 49 additions and 0 deletions

View File

@@ -146,6 +146,9 @@ namespace ICD.Common.Utils.Extensions
if (extends == null)
throw new ArgumentNullException("extends");
if (!extends.TokenType.IsPrimitive())
throw new FormatException("Expected primitive token type but got " + extends.TokenType);
return extends.Value == null ? null : extends.Value.ToString();
}

View File

@@ -0,0 +1,45 @@
using System;
using Newtonsoft.Json;
namespace ICD.Common.Utils.Extensions
{
public static class JsonTokenExtensions
{
/// <summary>
/// Returns true if the JsonToken respresents a single data value
/// rather than a complex type such as an object or an array.
/// </summary>
/// <param name="extends"></param>
/// <returns></returns>
public static bool IsPrimitive(this JsonToken extends)
{
switch (extends)
{
case JsonToken.None:
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
case JsonToken.Undefined:
return false;
case JsonToken.PropertyName:
case JsonToken.Comment:
case JsonToken.Raw:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
throw new ArgumentOutOfRangeException("extends");
}
}
}
}

View File

@@ -110,6 +110,7 @@
<Compile Include="Extensions\ByteExtensions.cs" />
<Compile Include="Extensions\DayOfWeekExtensions.cs" />
<Compile Include="Extensions\JsonSerializerExtensions.cs" />
<Compile Include="Extensions\JsonTokenExtensions.cs" />
<Compile Include="Extensions\JsonWriterExtensions.cs" />
<Compile Include="Extensions\ListExtensions.cs" />
<Compile Include="Comparers\PredicateEqualityComparer.cs" />