I am getting an error like this when I am trying to get data from another API.
Here is the controller code to call API
public async Task<IActionResult> Index()
{
List<Author>? AuthorList = new List<Author>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:5001/api/Authors"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
AuthorList = JsonConvert.DeserializeObject<List<Author>>(apiResponse);
}
}
return View(AuthorList);
}
2
Answers
From the error what I could understand is from the API you’re getting a JSON object – not a JSON array. And in the code, you’re trying to deserialize
apiResponse
which is anAuthor
object toList<Author>
.Either make changes in the API to return
List<Author>
or deserialize toAuthor
instead ofList<Author>
It would be better if you shared the replica of JSON too,
From the error, we can probably say that the list you are getting is in a single object… You should try something like this…
and then you should try something like below,
It will solve the error.