Search code examples
c#phparraysjsonrestsharp

Posting JSON array to PHP API via RestSharp C#


I am making an application with C#, in needs to post JSON array to my php api file. I have this code:

        string JSONString = JsonConvert.SerializeObject(dt);
        var client = new RestClient(ipadress);
        var request = new RestRequest(apiendpoint, Method.POST);
        request.RequestFormat = DataFormat.Json;
        var body = new
        {
            key = apikey,
            items = JSONString               

        };
        request.AddJsonBody(body);
        var response = client.Post(request);
        var content = response.Content; // Raw content as string
        MessageBox.Show(content.ToString());

So, the problem is that items = JSONString sends as string, not an array, and PHP API file is not enterpriting it as array (i cant extract values from rows). I did not found any information, how can i make 2nd level array in RestSharp, like (it is just imaginary code, it do not works:

var body = new
    {
        key = apikey,
        items = { 
           foreach(DataRow row in dt.Rows)
              {
                 aid = row["aid"].ToString(),
                 item= row["item"].ToString(),
                 desc= row["desc"].ToString()
              }
       }               

    };

My PHP api file (for information purposes,i am using framework):

$resultArray = array_map("html_entity_decode", $data);
foreach ($resultArray as $items) {
    $db->insert("test_items", ["aid"=>$items->aid, "item"=>$items->item, "desc"=>$items->desc]);
}
dnd($resultArray['items']);

Solution

  • You can do it like this, C# support anonymous types pretty well, so you can emit any desired POCO schema:

    In compilation time (strict API, all properties known, no need for switching somethin on/off) we do it like so:

    var body = new
        {
            key = apikey,
            items = dt
                  .Rows
                  .Cast<DataRow>() 
                  .Select(x=> new
                  {
                     aid = x["aid"].ToString(),
                     item= x["item"].ToString(),
                     desc= x["desc"].ToString()
                  })
                  .ToList()
           }
        };
    

    In runtime (if your set of properties will be known only at runtime) we do it like so:

    dynamic body = new ExpandoObject();
    body.key = apiKey;
    body.items = dt
                  .Rows
                  .Cast<DataRow>() 
                  .Select(x=> new
                  {
                     aid = x["aid"].ToString(),
                     item= x["item"].ToString(),
                     desc= x["desc"].ToString()
                  })
                  .ToList();