mustafasamet
mustafasamet

Reputation: 39

JSON convert array type to list in C#

I have some array data coming from an API in JSON format, and I want to convert an array type to a list. There is an ASP.NET MVC project and I used the list in Index page. How can I deserialize the array format into a list?

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

Data

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

Entity

public class Country
{
    [Key]
    public int Id { get; set; }
    public string CountryName { get; set; }
}

Upvotes: 0

Views: 793

Answers (4)

Serge
Serge

Reputation: 43880

you have to parse and use JArray inside of your result

var countries = JObject.Parse(results)["data"].ToObject<List<Country>>();

// data for test

var results =   @"{""data"": [
{
  ""id"": 1,
  ""countryName"": ""Afghanistan""
},
{
  ""id"": 2,
  ""countryName"": ""Albania""
},
{
  ""id"": 3,
  ""countryName"": ""Algeria""
}]}";

Upvotes: 0

Ramin Quliyev
Ramin Quliyev

Reputation: 380

Your json data is invalid format. Json maybe have to be like this:

{

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

After that you should create 2 c# class like this:

public class JsonData
{
    public List<Country> data { get; set; }
}

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

Then you can deserialize it without any error.

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<JsonData>(results);
        }

        return View(countries);
    }

Upvotes: 1

tmaj
tmaj

Reputation: 35017

The structure shown is not a list/array of Countries but an object which has a property data which is a list/array of Contries:

public class Result
{
   public List<Country> Data {get; set;}
}

...

var r = JsonConvert.DeserializeObject<Result>(results);
var countries = r.Data;

Minor note. Since you're using Json.NET it's OK that your properties don't match the case in json, but if you switch to System.Text.Json this would become an issue.

Upvotes: 0

JamesS
JamesS

Reputation: 2300

The object has a variable data that contains the countries whereas the class you're trying to serialize to does not.

Having a class such as:

public class Country{
    [JsonProperty('data')]
    public List<data> Details {get;set;}

    public Country(){
        Details = new List<data>();
    
}

public class data{
    [Key]
    [JsonProperty('id')]
    public int Id { get; set; }

    [JsonProperty('countryName')]
    public string CountryName { get; set; }     
}

and then to deserialize it you would need:

 countries = JsonConvert.DeserializeObject<Country>(results);

When it deserializes the object it will map data to the Details variable in the class Country and map each value in the response array to the data class

Upvotes: 0

Related Questions