使用C#将数组值发布到json API

时间:2017-09-21 14:05:28

标签: c# arrays json webclient httpresponse

我试图向在线API发送帖子请求以接收网络数据,但是使用正常的键值成功,但没有使用数组作为值,我可以&#39 ;在互联网上找到它而不创建大量的额外课程。

这就是我试图用普通数据发布到url的方式(第3个需要一个数组而不是单个对象)。

 IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
        {
               new KeyValuePair<string, string>("keyA","ValueA"),
               new KeyValuePair<string, string>("keyB", ""),
               new KeyValuePair<string, string>("KeyC", "ValueCDE"), //array
        };
        HttpContent q = new FormUrlEncodedContent(queries);
        Console.WriteLine(q.ToString());
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.PostAsync(url, q))
            {
                using (HttpContent content = response.Content)
                {
                    string mycontent = await content.ReadAsStringAsync();
                    HttpContentHeaders headers = content.Headers;
                    Console.WriteLine(mycontent);
                    Console.WriteLine(response);
                }
            }
        }

我尝试将原始数据发送到网址但我没收到任何回复。

    async static void PostRawRequest(string url)
    {
        string rawr = @"{
       ""a"":""a"",
       ""b"":"""",
       ""c"": [""C"", ""D"",""F""],
       ""StickerColor"": ""red""
       }";

        string result = "";
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            result = client.UploadString(url, "POST", rawr);
        }
        Console.WriteLine(result);

}

任何人都可以在第一个(发送数组值)或第二个(发送原始数据)中帮助我吗?

1 个答案:

答案 0 :(得分:1)

如果可以,请使用库来为您处理序列化。然后你可以做这样的事情(使用Newtonsoft.Json):

using (var client = new HttpClient())
{
    var json = JsonConvert.SerializeObject(yourObject);
    client.PostAsync(yourUri, new StringContent(json, Encoding.UTF8, "application/json"));
}