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);
6
  • 1
    The snippet does not look like valid JSON. Are you missing enclosing "{}"? Commented Jul 29, 2019 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 Commented Jul 29, 2019 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. Commented Jul 29, 2019 at 12:01
  • And using an Int based List, didn't work as well when passing it with AddJsonBody or AddParameter as well Commented Jul 29, 2019 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? Commented Jul 29, 2019 at 16:38

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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

}

Comments

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();

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.