如何从嵌套数组调用对象

时间:2020-05-26 02:44:23

标签: json flutter dart

希望将公共[api]用于个人项目。这是完整json数据集的摘要。

"Countries": [
    {
      "Country": "ALA Aland Islands",
      "CountryCode": "AX",
      "Slug": "ala-aland-islands",
      "NewConfirmed": 0,
      "TotalConfirmed": 0,
      "NewDeaths": 0,
      "TotalDeaths": 0,
      "NewRecovered": 0,
      "TotalRecovered": 0,
      "Date": "2020-04-05T06:37:00Z"
    },

我试图访问数组中的对象,甚至尝试了一些在这里看到的答案,但是它对我不起作用,要么是我一直显示“正在加载数据...”屏幕,要么是白屏显示。没有错误。 我的以下代码段

class CountriesData {
  String country;
  String countryCode;
  int confirmed;
  int deaths;
  int recovered;
  int active;
  DateTime date;

  CountriesData(this.country, this.countryCode, this.confirmed, this.deaths, 
      this.recovered, this.active, this.date);

  CountriesData.json(Map<String, dynamic> json) {
    country = json['Country'];
    countryCode = json['CountryCode'];
    confirmed = json['Confirmed'];
    deaths = json['Deaths'];
    recovered = json['Recovered'];
    active = json['Active'];
    date = DateTime.parse(json['Date']);
  }
}

1 个答案:

答案 0 :(得分:1)

似乎您从未解析过JSON。要使用JSON中的值,您需要先转换为Map。您必须导入dart:convert库,然后才能使用函数json.decode(jsonData)。这将返回一个地图,您可以用来从中获取数据。

var jsonData = fetchJson();
var parsedJson = json.decode(jsonData);
var x = CountriesData.json(parsedJson);
相关问题