[ObjectExtensions] Add ToByteArray/ConvertToString methods to byte[] and string, make ToDictionary considering property name preferably by JsonPropertyAttribute

This commit is contained in:
ChronosX88 2020-06-26 22:56:36 +04:00
parent 0e8bb5d1b7
commit eed6727b61

View File

@ -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<T>(value))
dictionary.Add(property.Name, (T)value);
{
var jsonProp = property.Attributes.OfType<JsonPropertyAttribute>().FirstOrDefault();
string propName;
if (jsonProp == null)
{
propName = property.Name;
}
else
{
propName = jsonProp.PropertyName;
}
dictionary.Add(propName, (T)value);
}
}
private static bool IsOfType<T>(object value)
@ -46,5 +60,15 @@ namespace Zirconium.Utils
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);
}
}
}