JSON数据转换为查询字符串在C#中的GET请求(Convert JSON data to quer

2019-09-23 02:22发布

什么是一个JSON对象转换为查询字符串追加到一个GET网址的最佳方式? 该POST是直线前进,并得到通过我的Web API的后端读取。

{名称:“迈克”} =名=麦克

 private static string MakeRequest(HttpWebRequest req, string data)
            {
                try
                {
                    if (req.Method == Verbs.POST.ToString() || req.Method == Verbs.PUT.ToString() || req.Method == Verbs.DELETE.ToString())
                    {
                        var encodedData = Encoding.UTF8.GetBytes(data);

                        req.ContentLength = encodedData.Length;
                        req.ContentType = "application/json";
                        req.GetRequestStream().Write(encodedData, 0, encodedData.Length);
                    }

                    using (var response = req.GetResponse() as HttpWebResponse)
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        return reader.ReadToEnd();
                    }
                }
                catch (WebException we)
                {
                    if(we.Response == null)
                    {
                        return JsonConvert.SerializeObject(new { Errors = new List<ApiError> { new ApiError(11, "API is currently unavailable") }});
                    }

                    using (var response = we.Response as HttpWebResponse)
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        return reader.ReadToEnd();
                    }
                }


  }

Answer 1:

如果JSON对象是平的,如你的榜样,那么

string json = @"{
    ""name"": ""charlie"",
    ""num"": 123
}";

var jObj = (JObject)JsonConvert.DeserializeObject(json);

var query = String.Join("&",
                jObj.Children().Cast<JProperty>()
                .Select(jp=>jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));

查询将被name=charlie&num=123



Answer 2:

我有这样的代码在.net内核上运行:

public static string JsonToQuery(this string jsonQuery)
    {
        string str = "?";
        str += jsonQuery.Replace(":", "=").Replace("{","").
                    Replace("}", "").Replace(",","&").
                        Replace("\"", "");
        return str;
    }

例:

var _baseURI = "http://www.example.com/";
var endPoint = "myendpoint";
ExampleObjectModel requestModel = new ExampleObjectModel();
var requestModelJson = JsonConvert.SerializeObject(requestModel);
var url = string.Format("{0}{1}{2}", _baseURI, endPoint, requestModelJson.JsonToQuery());


Answer 3:

试试这个,工作的所有对象,在深

 public static class ExtensionMethods
{
    public static string GetQueryString(this object obj, string prefix = "")
    {
        var query = "";
        try
        {
            var vQueryString = (JsonConvert.SerializeObject(obj));

            var jObj = (JObject)JsonConvert.DeserializeObject(vQueryString);
            query = String.Join("&",
               jObj.Children().Cast<JProperty>()
               .Select(jp =>
               {
                   if (jp.Value.Type == JTokenType.Array)
                   {
                       var count = 0;
                       var arrValue = String.Join("&", jp.Value.ToList().Select<JToken, string>(p =>
                       {
                           var tmp = JsonConvert.DeserializeObject(p.ToString()).GetQueryString(jp.Name + HttpUtility.UrlEncode("[") + count++ + HttpUtility.UrlEncode("]"));
                           return tmp;
                       }));
                       return arrValue;
                   }
                   else
                       return (prefix.Length > 0 ? prefix + HttpUtility.UrlEncode("[") + jp.Name + HttpUtility.UrlEncode("]") : jp.Name) + "=" + HttpUtility.UrlEncode(jp.Value.ToString());
               }
               )) ?? "";
        }
        catch (Exception ex)
        {

        }
        return query;
    }
}

使用方法:SomeObject.GetQueryString();



文章来源: Convert JSON data to querystring in C# GET request