前言
public static class UrlHelper { public static string ObjectToQuery<T>(this T obj, bool isAddEmptyValue = true, string orderBy = null, string removeFiled = null /*移除那个字段*/, string fieldReplace = null /*格式old,name*/) where T : class { if (obj == null) { return ""; } var properties = obj.GetType().GetProperties(); var list = new List<string>(); foreach (var item in properties) { if (removeFiled != null && item.Name == removeFiled) { //移除不必要字段 continue; } var proValue = item.GetValue(obj, null); if ((proValue != null && !string.IsNullOrEmpty(proValue.ToString())) || isAddEmptyValue) { var value = proValue != null ? proValue.ToString() : ""; value = value.Replace("+", "%20"); var filedName = item.Name; //替换key名字,如xxx_Name替换为xxx[0].Name if (!string.IsNullOrEmpty(fieldReplace)) { var arry = fieldReplace.Split(‘$‘); if (arry.Length > 1) { filedName = filedName.Replace(arry[0], arry[1]); } } list.Add(filedName + "=" + value); } } if (orderBy != null) { switch (orderBy) { case "asc": { list = list.OrderBy(m => m).ToList(); break; } default: { list = list.OrderByDescending(m => m).ToList(); break; } } } return string.Join("&", list); } }
class Program { static void Main(string[] args) { TestRequest testRequest = new TestRequest() { contactMobile = "133xxxxxxx", contactUser = "测试", passengers__idNumber = "440103xxxxxxxx", passengers__idType = "1", passengers__name = "测试" }; Console.WriteLine("{0}", UrlHelper.ObjectToQuery(testRequest,fieldReplace:"__$[0].",removeFiled:"contactUser")); Console.ReadLine(); } }
结果为:
原文:http://www.cnblogs.com/DiligentAnt/p/5927434.html