Search code examples
c#webrequest

How to create an array in JSON?


How can I post an HTTP request like this? I tried to make something like this, but I don't know how to make the [] section. Thanks for help!

{
  "ID": 1,
  "calls": [
    {
      "number": 702061966,
      "duration": "00:02:21",
      "date" : "2020-11-26 12:45:00"
    },
    {
      "number" : 123456789,
      "duration" : "00:15:48",
      "date" : "2020-11-27 08:23:00"
      },
      {
      "number" : 123456789,
      "duration" : "00:09:33",
      "date" : "2020-11-28 16:02:00"
    }
  ]
}

Solution

  • First you need a structure to represent the data in C#. For the given JSON this may look like so:

    public record MyRequest(int ID, IEnumerable<MyItem> Calls);
    public record MyItem(int Number, string Duration, string Date);
    

    Now you create the request

    var req = new MyRequest(1, new List<MyItem> {
      new MyItem(702061966, "00:02:21", "2020-11-26 12:45:00"),
      ...
    });
    

    ... and send it

    var response = await httpClient.PostAsJson("some/url", req);
    

    Code examples are intended as a first orientation and not tested. You can read more about it here:

    I dont know how to make [] section

    Any collection (IEnumerable<>, List<>, ...) will serialize to JSON list.

    Notes:

    • Code examples use c# 9 features
    • You may want to use other data types than strings e.g. DateTime