繁体   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