簡體   English   中英

JSON 將數組類型轉換為 C# 中的列表

[英]JSON convert array type to list in C#

我有一些來自 JSON 格式的 API 的數組數據,我想將數組類型轉換為列表。 有一個 ASP.NET MVC 項目,我使用了Index頁面中的列表。 如何將數組格式反序列化為列表?

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": [
{
  "id": 1,
  "countryName": "Afghanistan"
},
{
  "id": 2,
  "countryName": "Albania"
},
{
  "id": 3,
  "countryName": "Algeria"
},

實體

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

您的 json 數據格式無效。 Json 可能必須是這樣的:

{

“數據”:[{“id”:1,“countryName”:“阿富汗”},{“id”:2,“countryName”:“阿爾巴尼亞”},{“id”:3,“countryName”:“阿爾及利亞" } ] }

之后,您應該像這樣創建 2 c# class :

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

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

然后你可以反序列化它而不會出現任何錯誤。

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

object 具有包含國家/地區的變量data ,而您嘗試序列化的 class 沒有。

有一個 class 例如:

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

然后反序列化它你需要:

 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

顯示的結構不是國家列表/數組,而是一個 object,其屬性數據是國家列表/數組:

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

...

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

小注。 由於您使用的是 Json.NET,因此您的屬性與 json 中的情況不匹配是可以的,但是如果您切換到 System.Text.Json,這將成為一個問題。

您必須在結果中解析和使用 JArray

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""
}]}";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM