在C# GET请求中将JSON数据转换为查询字符串

yb3bgrhw  于 2023-02-06  发布在  C#
关注(0)|答案(4)|浏览(209)

将JSON对象转换为查询字符串并附加到GET URL的最佳方法是什么?POST是直接的,并由我的Web API后端读取。
{Name:'迈克' } =?姓名=迈克

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();
                    }
                }

  }
yhxst69z

yhxst69z1#

如果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

kognpnkq

kognpnkq2#

我让这段代码运行在. 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());
qeeaahzv

qeeaahzv3#

试试这个,在深

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;
    }
}

要用途:某个对象.GetQueryString();

8fsztsew

8fsztsew4#

如果您对象(实体)具有类似于此实体的子实体:

public class Parent
{
    public Child childs { get; set; } = new Child();
    public int PageIndex { get; set; }
    public int? PageSize { get; set; }
}    
public class Child 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

您可以使用此代码进行构建查询:首先将实体模型转换为JObject并调用此方法:

public static string GetQueryString(this JObject jObj)
    {
        return String.Join("&",
             jObj.Children().Cast<JProperty>()
             .Select(jp =>
             {
                 if (jp.Value.Type == JTokenType.Object)
                 {
                     var arrValue = String.Join("&",
                     jObj.Values().Children().Cast<JProperty>()
                     .Select(jp => jp.Path + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
                     return arrValue;
                 }
                 else
                 {
                     var arrValue = String.Join("&", jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString()));
                     return arrValue;
                 }
             }
             )) ?? "";
    }

你可以得到像这样的查询字符串:

childs.Id=1&childs.Name="Test"&PageIndex=1&PageSize=1

相关问题