public static void Map <TTo>(IDictionary <string, object> dictionary, TTo instance) { var attr = BindingFlags.Public | BindingFlags.Instance; foreach (var prop in instance.GetType().GetProperties(attr)) { if (prop.CanWrite && dictionary.ContainsKey(prop.Name)) { var propType = prop.PropertyType; var dataValue = dictionary[prop.Name]; if (OnTypes.IsSimple(propType)) { var v = Convert.ChangeType(dataValue, propType); prop.SetValue(instance, v); } else { //TODO:when types match or are convertable, just assign if (false) { } //when corresponding prop name in the dictionary of complex type is a IDictionary<string, object> if (dataValue is IDictionary <string, object> ) { var v = TurnDictionaryIntoObject((IDictionary <string, object>)dataValue, propType); prop.SetValue(instance, v); } } } } }
public static IDictionary <string, object> TurnObjectIntoDictionary(object data) { var attr = BindingFlags.Public | BindingFlags.Instance; var dict = new Dictionary <string, object>(); foreach (var prop in data.GetType().GetProperties(attr)) { if (prop.CanRead) { if (OnTypes.IsClass(prop.GetValue(data).GetType()) && !OnTypes.IsSimple(prop.GetValue(data).GetType())) { dict.Add(prop.Name, TurnObjectIntoDictionary(prop.GetValue(data))); } else { dict.Add(prop.Name, prop.GetValue(data, null)); } } } return(dict); }