Rk R Bairi
Rk R Bairi

Reputation: 1369

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

Upvotes: 4

Views: 17801

Answers (3)

user955340
user955340

Reputation:

values.ToString() will not create a valid JSON formatted string.

I'd recommend you use a JSON parser, such as Json.Net or LitJson to convert your Dictionary into a valid json string. These libraries are capable of converting generic objects into valid JSON strings using reflection, and will be faster than manually serialising into the JSON format (although this is possible if required).

Please see here for the JSON string format definition (if you wish to manually serialise the objects), and for a list of 3rd party libraries at the bottom: http://www.json.org/

Upvotes: 1

Nkosi
Nkosi

Reputation: 247471

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

Upvotes: 11

struggleendlessly
struggleendlessly

Reputation: 108

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?

Upvotes: 1

Related Questions