使用json.net实现复杂对象转换为QueryString

2021-01-17 02:11

阅读:406

标签:property   rom   util   json   each   for   void   复杂   enc   

目标:生成复杂对象的QueryString,比如{a:[{b:1},{b:2}]}这种

 

		[Test]
		public void 对象转QueryString()
		{
			var token = JToken.FromObject(new
			{
				Field1 = 1,
				Field2 = new
				{
					Field3 = "1",
					Field4 = new[]
					{
						new {Field5 = "2"},
						new {Field5 = "3"}
					}
				},
				Field6 = new[] { "3", "anc", "汉字" },
				Fied7 = (string)null
			});
			var queryStr = GetQueryString(token);
			Console.WriteLine(queryStr);
		}

		public static string GetQueryString(JToken obj)
		{
			var list = new List();
			SetQueryStringList(obj, list);
			return string.Join("&", list);
		}

		private static void SetQueryStringList(JToken jToken, List 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 + "=" + HttpUtility.UrlEncode(jToken.ToString()));
				}
			}
		}

  结果:Field1=1&Field2.Field3=1&Field2.Field4[0].Field5=2&Field2.Field4[1].Field5=3&Field6[0]=3&Field6[1]=anc&Field6[2]=%e6%b1%89%e5%ad%97

使用json.net实现复杂对象转换为QueryString

标签:property   rom   util   json   each   for   void   复杂   enc   

原文地址:https://www.cnblogs.com/wpycs/p/13371089.html


评论


亲,登录后才可以留言!