From 42a5ffba05047c1443d2625bd5e3a3f4b2c11981 Mon Sep 17 00:00:00 2001 From: ChronosX88 Date: Thu, 8 Oct 2020 21:08:29 +0400 Subject: [PATCH] Add ToObject extension method to Dictionary --- src/Zirconium/Utils/ObjectExtensions.cs | 32 ++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/Zirconium/Utils/ObjectExtensions.cs b/src/Zirconium/Utils/ObjectExtensions.cs index e9d304f..90328a1 100644 --- a/src/Zirconium/Utils/ObjectExtensions.cs +++ b/src/Zirconium/Utils/ObjectExtensions.cs @@ -27,7 +27,7 @@ namespace Zirconium.Utils private static void AddPropertyToDictionary(PropertyDescriptor property, object source, Dictionary dictionary) { object value = property.GetValue(source); - if (IsOfType(value)) + if (value is T) { var jsonProp = property.Attributes.OfType().FirstOrDefault(); string propName; @@ -39,13 +39,39 @@ namespace Zirconium.Utils { propName = jsonProp.PropertyName; } + if (jsonProp.Required == Required.Default && value == null){ + return; + } dictionary.Add(propName, (T)value); } } - private static bool IsOfType(object value) + public static T ToObject(this IDictionary source) + where T : class, new() { - return value is T; + var someObject = new T(); + var someObjectType = someObject.GetType(); + + foreach (var item in source) + { + string propName = null; + foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(someObject)) { + var jsonProp = prop.Attributes.OfType().FirstOrDefault(); + if (jsonProp != null) { + if (jsonProp.PropertyName == item.Key) { + propName = prop.Name; + } + } + } + if (propName == null) { + propName = item.Key; + } + someObjectType + .GetProperty(propName) + .SetValue(someObject, item.Value, null); + } + + return someObject; } private static void ThrowExceptionWhenSourceArgumentIsNull()