How to post a JSON Array of Objects in RestSharp

2019-08-20 09:20发布

问题:

I need to pass a JSON Array of objects, here's an example of what it should look like in JSON:

   "categories": [
    {
      "id": 9
    },
    {
      "id": 14
    }
  ],

I can't figure out how to get it done by myself, I tried using Restsharp's request.AddBody() and request.AddParameter() but it didn't get me anywhere =/

var request = new RestRequest();
request.AddParameter("name", name);
// Category
request.AddParameter("categories", "categories here");
var response = client.Post(request);

回答1:

If I understand it right you want to post a JSON Array. If you don't want to form a JSON string manually the easiest way is to use Newtonsoft.Json

Here is an example to you:

List<int> data = new List<int>() // This is your array

string JsonData = JsonConvert.SerializeObject(data);

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            StringContent content = new StringContent(JsonData, Encoding.UTF8, "application/json");

            HttpResponseMessage result = await client.PostAsync("your adress", content);

This is the easy way to make a POST request to a server.

To read the response you can use:

string answer = await result.Content.ReadAsStringAsync();


回答2:

This should work:

request.RequestFormat = DataFormat.Json; // Important

var input = new Dictionary<string, object>();
// cats can be an array on real objects too
var cats = new[] {new {id = 9}, new {id = 14}};
input.Add("categories", cats);

request.AddBody(input);