目标:生成复杂对象的QueryString,比如
new { Field1 = 1, Field2 = new { Field3 = "2", Field4 = new[] { new {Field5 = "4"}, new {Field5 = "5"} } }, Field6 = new[] { "3", "anc", "汉" }, Fied7 = (string)null }
[Test] public void 对象转QueryString() { var token = JToken.FromObject(new { Field1 = 1, Field2 = new { Field3 = "2", Field4 = new[] { new {Field5 = "4"}, new {Field5 = "5"} } }, Field6 = new[] { "3", "anc", "汉" }, Fied7 = (string)null }); var queryStr = GetQueryString(token); Console.WriteLine(queryStr); } public static string GetQueryString(JToken obj) { var list = new List<string>(); SetQueryStringList(obj, list); return string.Join("&", list); } private static void SetQueryStringList(JToken jToken, List<string> queryStrList) { if (jToken.Type == JTokenType.Array || jToken.Type == JTokenType.Object || jToken.Type == JTokenType.Property) { foreach (var item in jToken) { SetQueryStringList(item, queryStrList); } } else { if (jToken.Type != JTokenType.Null && jToken.Type != JTokenType.None) { queryStrList.Add(jToken.Path + "=" + Uri.EscapeUriString(jToken.ToString())); } } }
结果:Field1=1&Field2.Field3=2&Field2.Field4[0].Field5=4&Field2.Field4[1].Field5=5&Field6[0]=3&Field6[1]=anc&Field6[2]=%E6%B1%89