mirror of
https://github.com/cadmium-im/zirconium-sharp.git
synced 2024-11-22 10:22:23 +00:00
[ObjectExtensions] Add ToByteArray/ConvertToString methods to byte[] and string, make ToDictionary considering property name preferably by JsonPropertyAttribute
This commit is contained in:
parent
0e8bb5d1b7
commit
eed6727b61
@ -1,6 +1,8 @@
|
|||||||
|
using System.Linq;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
namespace Zirconium.Utils
|
namespace Zirconium.Utils
|
||||||
{
|
{
|
||||||
@ -26,7 +28,19 @@ namespace Zirconium.Utils
|
|||||||
{
|
{
|
||||||
object value = property.GetValue(source);
|
object value = property.GetValue(source);
|
||||||
if (IsOfType<T>(value))
|
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)
|
private static bool IsOfType<T>(object value)
|
||||||
@ -46,5 +60,15 @@ namespace Zirconium.Utils
|
|||||||
TValue value;
|
TValue value;
|
||||||
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user