mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-10 18:24:53 +00:00
Util method for casting a JSON token to a known type
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
using ICD.Common.Utils.IO;
|
||||
using ICD.Common.Utils.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace ICD.Common.Utils.Tests.Json
|
||||
@@ -140,6 +141,32 @@ namespace ICD.Common.Utils.Tests.Json
|
||||
Assert.AreEqual("test message", messageName);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeTypeTest()
|
||||
{
|
||||
const string json = "{\"test\":10}";
|
||||
|
||||
JObject root = JObject.Parse(json);
|
||||
JToken token = root["test"];
|
||||
|
||||
int value = (int)JsonUtils.Deserialize(typeof(int), token);
|
||||
|
||||
Assert.AreEqual(10, value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeTestSerializerTest()
|
||||
{
|
||||
const string json = "{\"test\":10}";
|
||||
|
||||
JObject root = JObject.Parse(json);
|
||||
JToken token = root["test"];
|
||||
|
||||
int value = (int)JsonUtils.Deserialize(typeof(int), token, new JsonSerializer());
|
||||
|
||||
Assert.AreEqual(10, value);
|
||||
}
|
||||
|
||||
public sealed class TestSerializable
|
||||
{
|
||||
private const string PROPERTY_NAME = "Test";
|
||||
|
||||
@@ -260,5 +260,29 @@ namespace ICD.Common.Utils.Json
|
||||
},
|
||||
json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the given token based on the known type.
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public static object Deserialize(Type type, JToken token)
|
||||
{
|
||||
return Deserialize(type, token, new JsonSerializer());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the given token based on the known type.
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <param name="serializer"></param>
|
||||
/// <returns></returns>
|
||||
public static object Deserialize(Type type, JToken token, JsonSerializer serializer)
|
||||
{
|
||||
using (JTokenReader jsonReader = new JTokenReader(token))
|
||||
return serializer.Deserialize(jsonReader, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user