Skip to content

Instantly share code, notes, and snippets.

@Wind010
Last active December 22, 2019 03:01
Show Gist options
  • Save Wind010/0644e86c0b03cfd9ad63124cd8ff244d to your computer and use it in GitHub Desktop.
Save Wind010/0644e86c0b03cfd9ad63124cd8ff244d to your computer and use it in GitHub Desktop.
Extensions for objects.
using GraphQL;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Reflection;
namespace Extensions
{
public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> dict)
where T : class, new()
{
var json = JsonConvert.SerializeObject(dict, new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// The object must be a non-primative and does not originate from the System namespace.
/// </summary>
/// <param name="source"></param>
/// <param name="camelCase">CamelCase keys</param>
/// <param name="depth">Current recursion depth.</param>
/// <param name="maxDepth">Maximum recursion depth.</param>
/// <returns><see cref="IDictionary{string, object}"></see></returns>
public static IDictionary<string, object> AsDictionary(this object source
, bool camelCase, uint depth = 0, int maxDepth = 10)
{
var dict = new Dictionary<string, object>();
const string System = "System";
if (source == null || source.GetType().Namespace.StartsWith(System))
{
return dict;
}
depth++;
if (depth >= maxDepth)
{
return dict;
}
foreach (PropertyInfo propInfo in source.GetType().GetProperties())
{
string propertyName = propInfo.Name.ToCamelCase();
// IsPrimative and IsClass won't work for types such as string, decimal, etc.
if (propInfo.GetValue(source, null).GetType().Namespace.StartsWith(System))
{
if (! camelCase)
{
propertyName = propInfo.Name;
}
dict.Add(propertyName, propInfo.GetValue(source, null));
continue;
}
//int maxRecursion = 10
dict.Add(propertyName, propInfo.GetValue(source, null).AsDictionary(camelCase, depth, maxDepth));
}
return dict;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment