1

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);
Milo
  • 3,365
  • 9
  • 30
  • 44
CodingCode
  • 123
  • 2
  • 12
  • 1
    The snippet does not look like valid JSON. Are you missing enclosing "{}"? – Fildor Jul 29 '19 at 11:04
  • 1
    _"It is recommended to use AddJsonBody or AddXmlBody methods instead of AddParameter with type BodyParameter. Those methods will set the proper request type and do the serialization work for you."_ from [RestSharp WIKI](https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest) – Fildor Jul 29 '19 at 11:12
  • @Fildor what's invalid in the JSON? were you talking about the commas in the end? if so, it's a typo. – CodingCode Jul 29 '19 at 12:01
  • And using an Int based List, didn't work as well when passing it with _AddJsonBody_ or _AddParameter_ as well – CodingCode Jul 29 '19 at 12:02
  • @CodingCode Are you trying to post just the array (the part in square brackets), or are you trying to post an object with a property called "categories" containing an array? – Brian Rogers Jul 29 '19 at 16:38
  • Hey, @BrianRogers I'm trying to post a parameter called "categories" which it's value, is an array of objects. each object inside it contains a single numeric property called id – CodingCode Jul 29 '19 at 17:09

3 Answers3

1

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);
LucasMetal
  • 1,323
  • 10
  • 16
1

Create a class and give it any name

class MyObject
{
   private int id;
   public MyObject(int id)
   {
     this.id = id;
   }
}

Define your class as an object

MyObject obj = new MyObject(9);

Now using Newtonsoft.Json serialize your object

string result = JsonConvert.SerializeObject(obj);

Now add it to an array

var resArray = new object[] { result };

Find the Complete code below

    class MyObject
    {
       private int id;
       public MyObject(int id)
       {
         this.id = id;
       }
    }


using Newtonsoft.Json;
using RestSharp;
class Main
{
    MyObject obj = new MyObject(9);
    MyObject obj1 = new MyObject(14);
    string result = JsonConvert.SerializeObject(obj);
    string result1 = JsonConvert.SerializeObject(obj1);

    var resArray = new object[] { result ,result1};

    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | 
    SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | 
    SecurityProtocolType.Tls;

    var client = new RestClient("http://127.0.0.1:8080");
    var request = new RestRequest("category", Method.POST);

    request.AddHeader("Content-Type", "application/json");
          
    request.AddJsonBody(new
    {
         categories = resArray,      
     }) ;

    var response = client.Execute(request);

    MessageBox.Show(response.IsSuccessful.ToString());
         
    MessageBox.Show(response.Content);

}
Herbert
  • 75
  • 8
0

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();
  • I was trying to get it done using a combination of the answers here, sadly it didn't work. I have only used your serialization tip, I guess I'll need to check your request code as well. – CodingCode Jul 29 '19 at 12:03