简体   繁体   中英

JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List

When I consume the Web API in the MVC project I encountered this error but I cannot fix this error. How can I solve this? My API is clearly working but MVC is doesn't work.

Controller

public async Task<IActionResult> ListCountries()
    {
        List<Country> countries = new List<Country>();
        HttpClient _client = new HttpClient();
        HttpResponseMessage _response = new HttpResponseMessage();
        _client = _apiHelper.Initial();
        _response = await _client.GetAsync("api/Countries/getall");
        if (_response.IsSuccessStatusCode)
        {
            var results = _response.Content.ReadAsStringAsync().Result;
            countries = JsonConvert.DeserializeObject<List<Country>>(results);
        }   

        return View(countries);
    }

JSON Data

"data": [
{
  "id": 1,
  "countryName": "Afghanistan"
},
{
  "id": 2,
  "countryName": "Albania"
},
{
  "id": 3,
  "countryName": "Algeria"
},

If you built the Web Api change its response from

"data": [
{
  "id": 1,
  "countryName": "Afghanistan"
},
{
  "id": 2,
  "countryName": "Albania"
},
{
  "id": 3,
  "countryName": "Algeria"
}]

To

 [
        {
          "id": 1,
          "countryName": "Afghanistan"
        },
        {
          "id": 2,
          "countryName": "Albania"
        },
        {
          "id": 3,
          "countryName": "Algeria"
        }
]

Create the object and cast it from json response to object

public class Data
    {
        public int id { get; set; }
        public string countryName { get; set; }
    }

    public class Root
    {
        public List<Data> data { get; set; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM