C#反射遍历对象属性将对象属性拼接成QueryString字符串按照字母先后顺序排列

最近开发中遇到需要将对象属性动态拼接成querystring格式并要求根据key的字母顺序进行升序排列拼接字符串,记录相关技术细节。后面备用

    public class ForeachClass
    {
        /// <summary>
        /// C#反射遍历对象属性
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="model">对象</param>
        public static ClassPropertyAttrModle ForeachClassProperties<T>(T model, string[] excKeys = null)
        {
            ClassPropertyAttrModle results = new ClassPropertyAttrModle();
            Type t = model.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            foreach (PropertyInfo item in PropertyList)
            {
                string name = item.Name;
                object value = item.GetValue(model, null);
                if (!CheckKeyIsExists(excKeys, name))
                {
                    results.keys.Add(name);
                    results.Values.Add(value);
                }
            }
            return results;
        }
        /// <summary>
        /// 检验指定数组中是否存在指定字符串
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static bool CheckKeyIsExists(string[] keys, string value)
        {
            bool res = false;
            if (keys != null && keys.Length > 0)
            {
                foreach (var item in keys)
                {
                    if (item == value)
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 获取对象属性名称和值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>用&拼接的结果</returns>
        public static string GetPropertyNameAndValue(object obj)
        {
            if (obj == null) { return string.Empty; }
            StringBuilder result = new StringBuilder();
            try
            {
                System.Reflection.PropertyInfo[] propertys = obj.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    object valueObj = pi.GetValue(obj, null);
                    if (valueObj == null) { continue; }
                    Type valueType = valueObj.GetType();
                    if (valueType != typeof(object) && Type.GetTypeCode(valueType) == TypeCode.Object)//判断是自定义类
                    {
                        System.Reflection.PropertyInfo[] classProperty = valueType.GetProperties();
                        foreach (PropertyInfo property in classProperty)
                        {
                            object childValueObj = property.GetValue(valueObj, null);
                            if (childValueObj == null) { continue; }
                            result.Append(pi.Name + "." + property.Name + "=" + childValueObj.ToString() + "&");
                        }
                    }
                    else
                    {
                        result.Append(pi.Name + "=" + valueObj.ToString() + "&");
                    }
                }
            }
            catch (Exception)
            {
            }
            return result.ToString().TrimEnd('&');
        }


        public static string urlParamManager(JObject postArray, string[] exKeys)
        {
            ArrayList keys = new ArrayList();
            foreach (JToken child in postArray.Children())
            {
                JProperty property = child as JProperty;
                if (exKeys!=null)
                {
                    if (!exKeys.Contains(property.Name))
                    {
                        keys.Add(property.Name);
                    }
                }
                else
                {
                    keys.Add(property.Name);
                }
            }
            keys.Sort();
            StringBuilder sb = new StringBuilder();
            foreach (string key in keys)
            {
                if (!exKeys.Contains(key))
                {
                    if (!string.IsNullOrEmpty(postArray[key].Value<string>()))
                    {
                        var value = Uri.EscapeDataString(postArray[key].Value<string>());
                        value = postArray[key].Value<string>();
                        if (string.IsNullOrEmpty(sb.ToString()))
                        {
                            
                            sb.Append(key + "=" +value);
                        }
                        else
                        {
                            sb.Append("&" + key + "=" + value);
                        }
                    }
                }
                else
                {
                    var value = Uri.EscapeDataString(postArray[key].Value<string>());
                    value = postArray[key].Value<string>();
                    if (string.IsNullOrEmpty(sb.ToString()))
                    {

                        sb.Append(key + "=" + value);
                    }
                    else
                    {
                        sb.Append("&" + key + "=" + value);
                    }
                }
            }
            return sb.ToString();
        }
    }
    /// <summary>
    /// 类的属性键值提取
    /// </summary>
    public class ClassPropertyAttrModle
    {
        public List<string> keys { get; set; } = new List<string>();
        public List<object> Values { get; set; } = new List<object>();
    }

代码调用:

            var filterStr = "sign";
            var urlData = ForeachClass.urlParamManager(JObject.FromObject(data),filterStr.Split(','));
posted @ 2022-12-03 09:09  星火燎猿*  阅读(31)  评论(0编辑  收藏  举报