I have a NET Core MVC web application where I'm calling an API to show the results in my UI. I'm calling the API using an ajax call but after calling the API I get the following error message:
An unhandled exception occurred while processing the request. JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ProjectName.Models.ControllerName' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
JSON Result from API:
[
[
{
"Col1": "Value",
"Col2": "Value",
"Col3": "Value",
"Col4": [
{
"Value": [
{}
]
},
{
"Value": [
{}
]
}
],
"Col5": "Value"
}
],
[
{
"Col1": "Value",
"Col2": "Value",
"Col3": "Value",
"Col5": "Value"
}
],
[
{
"Col1": "Value",
"Col2": "Value",
"Col3": "Value",
"Col4": [
{
"Value": [
{}
]
},
{
"Value": [
{}
]
}
],
"Col5": "Value"
}
]
]
MyController
[HttpGet, ActionName("GetData")]
public async Task<IActionResult> GetReport()
{
return this.Json(await _cuRepo.GetReportAsync("https://apiurlforcall/report"));
}
Repository
public async Task<IEnumerable<T>> GetReportAsync(string url)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Token", "apiToken");
HttpResponseMessage response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//jsonString is populated with the above JSON result
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString);
}
else
return null;
}
}
AjaxCall (What I'm trying to do)
$.ajax({
url: "Controller/GetData",
data: {},
method: "GET",
success: function (data) {
var json = data;
var html = "";
for (var x = 0; x < json.length; x++) {
html += "<tr><td>" + json[x].Col1+ "</td><td>" + json[x].Col2+ "</td></tr>";
}
$('#MyTable').html("");
$('#MyTable').html(html);
console.log(json);
}
});
To be honest, I don't have too much experience with net core, I'm trying to learn by doing this project but this issue is a big roadblock and I'm kind of lost.