5

JSONオブジェクトをクエリ文字列に変換してGETURLに追加する最良の方法は何ですか?POSTは単純明快で、WebAPIバックエンドによって読み取られます。

{名前:'マイク'}=?名前=マイク

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


  }
4

3 に答える 3

21

あなたの例のように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

于 2012-09-26T21:38:53.297 に答える
0

これを試して、すべてのオブジェクトを深く操作してください

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

于 2018-10-06T06:58:46.880 に答える