| | |
| | | 锘縰sing System; |
| | | 锘縰sing Newtonsoft.Json; |
| | | using System; |
| | | using System.Collections.Generic; |
| | | using System.Linq; |
| | | using System.Reflection; |
| | |
| | | |
| | | public static T DicToModel<T>(this Dictionary<string, object> dic) |
| | | { |
| | | T model = Activator.CreateInstance<T>(); |
| | | PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); |
| | | #region |
| | | //T model = Activator.CreateInstance<T>(); |
| | | //PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); |
| | | |
| | | Dictionary<string, object> upperDic = dic.ToDictionary(k => k.Key.ToUpper(), v => v.Value); |
| | | //Dictionary<string, object> upperDic = dic.ToDictionary(k => k.Key.ToUpper(), v => v.Value); |
| | | |
| | | foreach (var property in propertyInfos) |
| | | //foreach (var property in propertyInfos) |
| | | //{ |
| | | // object value = null; |
| | | // if (!upperDic.TryGetValue(property.Name.ToUpper(), out value)) |
| | | // { |
| | | // continue; |
| | | // } |
| | | // property.SetValue(model, value?.ToString().ChangeType(property.PropertyType)); |
| | | //} |
| | | //return model; |
| | | #endregion |
| | | |
| | | T? model = Activator.CreateInstance<T>(); |
| | | try |
| | | { |
| | | object value = null; |
| | | if (!upperDic.TryGetValue(property.Name.ToUpper(), out value)) |
| | | model = JsonConvert.DeserializeObject<T>(dic.Serialize()); |
| | | } |
| | | catch{ } |
| | | if (model == null) |
| | | { |
| | | PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); |
| | | foreach (var property in propertyInfos) |
| | | { |
| | | continue; |
| | | object value = null; |
| | | if (!dic.TryGetValue(property.Name, out value)) |
| | | { |
| | | if (!dic.TryGetValue(property.Name.FirstLetterToUpper(), out value)) |
| | | { |
| | | if (!dic.TryGetValue(property.Name.FirstLetterToLower(), out value)) |
| | | { |
| | | continue; |
| | | } |
| | | } |
| | | }; |
| | | property.SetValue(model, value?.ToString().ChangeType(property.PropertyType)); |
| | | } |
| | | property.SetValue(model, value?.ToString().ChangeType(property.PropertyType)); |
| | | } |
| | | return model; |
| | | } |