json - 如何从嵌套数组中调用对象
问题描述
我希望将公共[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']);
}
}
解决方案
您似乎从未解析过 JSON。要使用 JSON 中的值,您需要先转换为 Map。您必须导入dart:convert
库,然后才能使用该功能json.decode(jsonData)
。这将返回一个可用于从中获取数据的地图。
var jsonData = fetchJson();
var parsedJson = json.decode(jsonData);
var x = CountriesData.json(parsedJson);
推荐阅读
- javascript - 正则表达式匹配jsx中的className
- scala - scala中列表的滑动和分组函数的时间复杂度是多少
- zsh - 分配非数组变量时的文件名扩展
- php - 在 laravel 中自定义电子邮件验证链接问题
- java - android studio 中没有显示错误,但 setOnClickListener 仅在一个按钮上有效,而在另一个按钮上无效
- angular - 如何使用多个角度版本?
- typescript - 如何过滤具有另一个数组中的值的数组?
- python - Pandas 将 dicts 列表附加到由 df1.apply 函数产生的 df2
- unix - 如何检索在不同脚本中运行的脚本的进程 ID
- c++ - 需要帮助查找死细胞数据*生命游戏* [已解决]