skip to Main Content

I am getting an error like this when I am trying to get data from another API.

Error Image

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


  1. 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 an Author object to List<Author>.

    Either make changes in the API to return List<Author> or deserialize to Author instead of List<Author>

    Login or Signup to reply.
  2. 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…

    public class Author
    {
        ...
        ...
        ...
    }
    public class AuthorObject
    {
       public List<Author> Authors { get; set; }
    }
    

    and then you should try something like below,

    AuthorObject obj = JsonConvert.DeserializeObject<AuthorObject>(apiResponse);
    

    It will solve the error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search