字典映射处理
正常情况下不同的终端在进行接口对接时会对传输的数据进行加密,在解密之后拿到字符串,要么直接用动态类型获取,但是又要对字段进行判空校验,非常麻烦,这里封装了实体映射的方法,直接把解密后的字符串进行解析,映射到对应的实体对象中,其中是包括单实体,以及包含带子表的实体映射。 如下
#region 字段映射 /// <summary> /// 字段映射 解密映射实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> public static T MapEntity<T>(this string input) where T : new() { T entity = new T();
//带正则表达式解析,没有可不要 MatchCollection matches = Regex.Matches(input, @"<(\w+):([^<>]+)>"); foreach (Match match in matches) { string key = match.Groups[1].Value; string value = match.Groups[2].Value; SetNullFieldData(key, value, entity); } return entity; } /// <summary> /// 字段映射 解密映射实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> public static T MapEntityV2<T, U>(this string input, string detailName) where T : new() where U : new() { T entity = new T();
//带正则表达式解析,没有可不要 MatchCollection matches = Regex.Matches(input, @"<(\w+):(.+?)>"); foreach (Match match in matches) { string key = match.Groups[1].Value; string value = match.Groups[2].Value; if (key == detailName) { // 解析子表数据 var subTableData = value.Split(';'); List<U> subTableEntities = new List<U>(); foreach (var subData in subTableData) { var subDataParts = subData.Split(','); U subTableEntity = new U(); foreach (var part in subDataParts) { var subParts = part.Split(':'); string subKey = subParts[0]; string subValue = subParts[1]; SetNullFieldData(subKey, subValue, subTableEntity); } subTableEntities.Add(subTableEntity); } // 将子表数据映射到主实体对象的属性中 var property = typeof(T).GetProperty(key); if (property != null) { property.SetValue(entity, subTableEntities); } } else { // 解析主表数据 SetNullFieldData(key, value, entity); } } return entity; } private static void SetNullFieldData<T>(string key, string value, T entity) { var property = typeof(T).GetProperty(key); if (property == null) { return; } if (property.PropertyType == typeof(int?) && int.TryParse(value, out int parsedValue)) { property.SetValue(entity, parsedValue); } else if (property.PropertyType == typeof(long?) && long.TryParse(value, out long longValue)) { property.SetValue(entity, longValue); } else if (property.PropertyType == typeof(short?) && short.TryParse(value, out short shortValue)) { property.SetValue(entity, shortValue); } else { property.SetValue(entity, Convert.ChangeType(value, property.PropertyType)); } } #endregion
大家好,我是新来的小白,文未佳,却已创。转载请声明(博客园-郎中令)出处,谢谢
---市人皆大笑,举手揶揄之(手动链接博客园)