user3515765 user3515765 - 1 month ago 15
C# Question

How to edit array to add keynames, from a httpclient api call in MVC?

I am very new to MVC and making api calls server side and need a little guidance. I have created a simple method to call an api to retrieve results in a JSON object:

apiController.cs (normal controller.cs file)

[HttpGet]
public JsonResult getDefaultStuff(string a = "abc") {
var url = "https://myapiurl";
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("Blah");
var response = client.GetStringAsync(url);
return Json(response, JsonRequestBehavior.AllowGet);
}


The results return in an array like this:

{Result: {examples: [[0000,6.121],[0000,1.122],[0000,9.172]]},"Id":81,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}


I need it to return with keynames like this :

{
"examples": [
{
"Keyname1": "45678",
"Keyname2": "1234"
},
{
"Keyname1": "14789",
"Keyname2": "1234"
},
{
"Keyname1": "12358",
"Keyname2": "4569"
}
]
}


Do I need to use IDictonary? I am unsure of the approach. Do I create a new object and then loop through each result adding keynames? an example would be much appreciated or just the approach will be very helpful.

Answer

You can do the following:

By using the Json.Net nuget package first deserialize the response into, for example, an anonymous object:

var deserialized = JsonConvert.DeserializeAnonymousType(response, new
{
    examples = new[] { new decimal[] { } }
});

Then transform this object into the new one that has the property structure you need:

var result = new
{
    examples = deserialized.Result.examples.Select(x => new
    {
        Keyname1 = x[0],
        Keyname2 = x[1]
    })
};

And return it to the client:

return Json(result, JsonRequestBehavior.AllowGet);

This is what your solution could roughly look like but you do have to keep several things in mind though:

  1. Exception handling for deserialization
  2. Checks for possible nulls in the deserialized object
  3. Maybe also the safer way of retrieving values from the array to avoid possible out of range exceptions.

Also the GetStringAsync method is asynchronous and you should put an await keyword in front of it, but in order to do so you need to make your method async as well:

public async Task<JsonResult> getDefaultStuff(...)

If you don't have enough knowledge of asynchronous programming, here is the most advanced, in-depth and comprehensive video explaining it from top to bottom I have ever seen, so check it out whenever you find time...

Comments