欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 将json字符串转换为键值对形式,用于执行form表单形式的请求

程序员文章站 2022-06-12 19:59:48
...

需要添加引用:

System.Web

System.Web.Extensions


需要引入命名空间:

using System.Collections.Generic;

using System.Web;

using System.Web.Script.Serialization;


 

string KeyValueCombination(string str)
        {
            string paraUrlCoded = "";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(str);
            foreach (var j in json)
            {
                paraUrlCoded += System.Web.HttpUtility.UrlEncode(j.Key);
                if (j.Value.GetType() == typeof(object[]))
                {
                    paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jss.Serialize(j.Value)) + "&";
                }
                else
                {
                    paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(j.Value.ToString()) + "&";
                }
            }


            if (!string.IsNullOrWhiteSpace(paraUrlCoded))
            {
                paraUrlCoded = paraUrlCoded.Substring(0, paraUrlCoded.Length - 1);
            }


            return paraUrlCoded;
        }