From eed6727b618d624c7e9e06037c8f7c3726169d67 Mon Sep 17 00:00:00 2001 From: ChronosX88 Date: Fri, 26 Jun 2020 22:56:36 +0400 Subject: [PATCH] [ObjectExtensions] Add ToByteArray/ConvertToString methods to byte[] and string, make ToDictionary considering property name preferably by JsonPropertyAttribute --- src/Zirconium/Utils/ObjectExtensions.cs | 28 +++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Zirconium/Utils/ObjectExtensions.cs b/src/Zirconium/Utils/ObjectExtensions.cs index f48e295..e9d304f 100644 --- a/src/Zirconium/Utils/ObjectExtensions.cs +++ b/src/Zirconium/Utils/ObjectExtensions.cs @@ -1,6 +1,8 @@ +using System.Linq; using System; using System.Collections.Generic; using System.ComponentModel; +using Newtonsoft.Json; namespace Zirconium.Utils { @@ -26,7 +28,19 @@ namespace Zirconium.Utils { object value = property.GetValue(source); if (IsOfType(value)) - dictionary.Add(property.Name, (T)value); + { + var jsonProp = property.Attributes.OfType().FirstOrDefault(); + string propName; + if (jsonProp == null) + { + propName = property.Name; + } + else + { + propName = jsonProp.PropertyName; + } + dictionary.Add(propName, (T)value); + } } private static bool IsOfType(object value) @@ -39,12 +53,22 @@ namespace Zirconium.Utils throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null."); } - public static TValue GetValueOrDefault (this IDictionary dictionary, + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, TValue defaultValue) { TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } + + public static byte[] ToByteArray(this string str) + { + return System.Text.Encoding.UTF8.GetBytes(str); + } + + public static string ConvertToString(this byte[] bytes) + { + return System.Text.Encoding.UTF8.GetString(bytes); + } } } \ No newline at end of file