-2
   [{
  "channel_id":299,
  "requests":[{
      "order_id":3975,
      "action":"REQUEST_LABELS"
  }]
}]

How to create the above request in c# the requests can be multiple.

I am new to c# i tried the below:

  Dictionary<long, List<object>> requestObject = new Dictionary<long, List<object>>();
        List<object> listrequestObjects = new List<object>();

            Request requestOb = new Request();
            requestOb.order_id = 2372;
            requestOb.action = "REQUEST_LABELS";
            listrequestObjects.Add(requestOb);
            requestObject.Add(2352635, listrequestObjects);
            string requesttest = JsonConvert.SerializeObject(requestObject);

But getting a weird request. Please help.

vini
  • 4,657
  • 24
  • 82
  • 170

4 Answers4

1

The structure should look like :

public class Request
{
    public int order_id { get; set; }
    public string action { get; set; }
}

public class RootObject
{
    public int channel_id { get; set; }
    public List<Request> requests { get; set; }
}
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
0

You need to declare the root object also:

[Serializable]
public class Root {
    public int channel_id;
    public Request[] requests;
}

Then assign the value and serialize it:

var root = new Root();
root.channel_id = 299;
root.requests = listrequestObjects.ToArray();
string requesttest = JsonConvert.SerializeObject(root);
Florian Gl
  • 5,984
  • 2
  • 17
  • 30
0

You can use Newtonsoft.Json.

try this

    private JArray GetResponse()
    {
        var main_array = new JArray();
        var channel_id = new JObject();
        channel_id.Add("channel_id",299);

        var request = new JArray();
        var order_id = new JObject();
        order_id.Add("order_id",3975);

        var action = new JObject();
        action.Add("action","REQUEST_LABELS");

        request.Add(order_id);
        request.Add(action);

        main_array.Add(channel_id);
        main_array.Add(request);

        return main_array;
    }
melihorhan
  • 198
  • 1
  • 2
  • 11
-1

Please try the JavaScriptSerializer class available in namespace using System.Web.Script.Serialization

JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(requestObject);

The requestObject list is your custom class with all necessary properties.

Thanks

Aju Mon
  • 225
  • 2
  • 15