Home > Enterprise >  Error in call API Json DeserializeObject in controller
Error in call API Json DeserializeObject in controller

Time:01-10

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);
}

CodePudding user response:

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>

CodePudding user response:

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.

  • Related