I'm learning on how to consume third-party API, (I don't have any control on how the data should be formatted).
I followed a tutorial online, an I'm stuck on this error I can't return a json. my data from API looks like this
{"status":1,"message":"","data":{"VacationLeave":11,"SickLeave":10,"EmergencyLeave":2,"HolidaySwap":1,"OldLeave":1}}
The error thats been thrown on compilation.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[HttpClientTest.Models.LeaveModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
my controller
public IActionResult Privacy()
{
//Fetch the JSON string from URL.
List<LeaveModel> leaves = new List<LeaveModel>();
string apiUrl = "http://xxx.xxx.xxx:83/GetLeaveBalance/2170";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(apiUrl).Result;
if (response.IsSuccessStatusCode)
{
leaves = JsonConvert.DeserializeObject<List<LeaveModel>>(response.Content.ReadAsStringAsync().Result);
}
//Return the Deserialized JSON object.
return Json(leaves);
}