using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Newtonsoft.Json; using Umbraco.Core.Collections; namespace Umbraco.Core { /// /// Provides object extension methods. /// public static class ObjectJsonExtensions { private static readonly ConcurrentDictionary> ToObjectTypes = new ConcurrentDictionary>(); /// /// Converts an object's properties into a dictionary. /// /// The object to convert. /// A property namer function. /// A dictionary containing each properties. public static Dictionary ToObjectDictionary(T obj, Func namer = null) { if (obj == null) return new Dictionary(); string DefaultNamer(PropertyInfo property) { var jsonProperty = property.GetCustomAttribute(); return jsonProperty?.PropertyName ?? property.Name; } var t = obj.GetType(); if (namer == null) namer = DefaultNamer; if (!ToObjectTypes.TryGetValue(t, out var properties)) { properties = new Dictionary(); foreach (var p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) properties[namer(p)] = ReflectionUtilities.EmitPropertyGetter(p); ToObjectTypes[t] = properties; } return properties.ToDictionary(x => x.Key, x => ((Func) x.Value)(obj)); } } }