4

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;
}
Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39

3 Answers3

11

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;
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 3
    Worth pointing out that both of these require the 3rd party library Json.Net (the latter being an extension method provided by that library). As of posting, the download location for Json.Net is: https://www.newtonsoft.com/json –  Aug 31 '17 at 14:46
  • 1
    @nkosi, just out of curiosity, which platforms are the ones that allow the use of PostAsJsonAsync? – Miguel Mateo May 03 '19 at 13:18
  • 1
    @MiguelMateo have a look at the API doc https://learn.microsoft.com/en-us/previous-versions/aspnet/hh944845%28v%3dvs.108%29 – Nkosi May 03 '19 at 17:06
1

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?

struggleendlessly
  • 108
  • 2
  • 2
  • 8
1

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/