[英]How to decode nested JSON List of Objects in Dart/Flutter
我試圖弄清楚如何在 Flutter 中解碼以下 JSON。
https://covid.ourworldindata.org/data/owid-covid-data.json
我嘗試了以下結構,但它不起作用。
@JsonSerializable()
class StatisticsResponse {
Map<String, Country> data;
//List<Country> data;
StatisticsResponse({this.data});
factory StatisticsResponse.fromJson(Map<String, dynamic> json) =>
_$StatisticsResponseFromJson(json);
}
@JsonSerializable()
class Country {
String continent;
String location;
int population;
//Map<String, Data> data;
List<Data> data;
Country({this.continent, this.location, this.population, this.data
});
factory Country.fromJson(Map<String, dynamic> json) =>
_$CountryFromJson(json);
}
使用 Map 將dynamic
轉換為String
。 直接將 List 分配給 List 會拋出錯誤。 您自己創建了吸氣劑。
考慮這個例子:
(jsonDecode(response.body)["data"] as List).map((e) => e as Map<String, dynamic>)?.toList();
現在分配給您創建的自定義 class 的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.