From 96fc6787a54ced121068dc9a2afc2c04747358fd Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Tue, 6 Feb 2018 12:01:46 -0500 Subject: [PATCH] Util method for casting a JSON token to a known type --- ICD.Common.Utils.Tests/Json/JsonUtilsTest.cs | 27 ++++++++++++++++++++ ICD.Common.Utils/Json/JsonUtils.cs | 24 +++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/ICD.Common.Utils.Tests/Json/JsonUtilsTest.cs b/ICD.Common.Utils.Tests/Json/JsonUtilsTest.cs index fe77594..49c5b3d 100644 --- a/ICD.Common.Utils.Tests/Json/JsonUtilsTest.cs +++ b/ICD.Common.Utils.Tests/Json/JsonUtilsTest.cs @@ -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"; diff --git a/ICD.Common.Utils/Json/JsonUtils.cs b/ICD.Common.Utils/Json/JsonUtils.cs index 2b17b57..2e0a46b 100644 --- a/ICD.Common.Utils/Json/JsonUtils.cs +++ b/ICD.Common.Utils/Json/JsonUtils.cs @@ -260,5 +260,29 @@ namespace ICD.Common.Utils.Json }, json); } + + /// + /// Deserializes the given token based on the known type. + /// + /// + /// + /// + public static object Deserialize(Type type, JToken token) + { + return Deserialize(type, token, new JsonSerializer()); + } + + /// + /// Deserializes the given token based on the known type. + /// + /// + /// + /// + /// + public static object Deserialize(Type type, JToken token, JsonSerializer serializer) + { + using (JTokenReader jsonReader = new JTokenReader(token)) + return serializer.Deserialize(jsonReader, type); + } } }