From fdfd8fe1c10ff16a53eed51d59f212d7a7aba171 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Tue, 5 Dec 2017 13:38:54 -0500 Subject: [PATCH] Implementing method for deserializing a message from json --- ICD.Common.Utils/Json/JsonUtils.cs | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/ICD.Common.Utils/Json/JsonUtils.cs b/ICD.Common.Utils/Json/JsonUtils.cs index 8d522c2..2b17b57 100644 --- a/ICD.Common.Utils/Json/JsonUtils.cs +++ b/ICD.Common.Utils/Json/JsonUtils.cs @@ -206,5 +206,59 @@ namespace ICD.Common.Utils.Json w.WriteEndObject(); }); } + + /// + /// Deserializes a json object wrapped in a json message structure. + /// E.g. + /// { a = 1 } + /// Becomes + /// { m = "Test", d = { a = 1 } } + /// + /// + /// + /// + [PublicAPI] + public static T DeserializeMessage(Func deserializeMethod, string json) + { + if (deserializeMethod == null) + throw new ArgumentNullException("deserializeMethod"); + + return Deserialize(r => + { + T output = default(T); + string messageName = null; + + while (r.Read()) + { + if (r.TokenType == JsonToken.EndObject) + { + r.Read(); + break; + } + + if (r.TokenType != JsonToken.PropertyName) + continue; + + string property = r.Value as string; + + // Read to the value + r.Read(); + + switch (property) + { + case MESSAGE_NAME_PROPERTY: + messageName = r.GetValueAsString(); + break; + + case MESSAGE_DATA_PROPERTY: + output = deserializeMethod(r, messageName); + break; + } + } + + return output; + }, + json); + } } }