首页 > 解决方案 > 如何从嵌套数组中调用对象

问题描述

我希望将公共[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']);
  }
}

标签: jsonflutterdart

解决方案


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

var jsonData = fetchJson();
var parsedJson = json.decode(jsonData);
var x = CountriesData.json(parsedJson);

推荐阅读