Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preparing Json Object for HttpClient Post method

I am trying to prepare a JSON payload to a Post method. The server fails unable to parse my data. ToString() method on my values would not convert it to JSON correctly, can you please suggest a correct way of doing this.

var values = new Dictionary<string, string>
{
    {
        "type", "a"
    }

    , {
        "card", "2"
    }

};
var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync(myUrl, data).Result;
using (HttpContent content = response.content)
{
    result = response.content.ReadAsStringAsync().Result;
}
like image 581
Rk R Bairi Avatar asked Sep 01 '25 18:09

Rk R Bairi


2 Answers

You need to either manually serialize the object first using JsonConvert.SerializeObject

var values = new Dictionary<string, string> 
            {
              {"type", "a"}, {"card", "2"}
            };
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");

//...code removed for brevity

Or depending on your platform, use the PostAsJsonAsync extension method on HttpClient.

var values = new Dictionary<string, string> 
            {
              {"type", "a"}, {"card", "2"}
            };
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
    result = response.Content.ReadAsStringAsync().Result;
}
like image 122
Nkosi Avatar answered Sep 04 '25 06:09

Nkosi


https://www.newtonsoft.com/json use this. there are already a lot of similar topics. Send JSON via POST in C# and Receive the JSON returned?

like image 41
struggleendlessly Avatar answered Sep 04 '25 06:09

struggleendlessly