简体   繁体   English

如何解码 Dart/Flutter 中嵌套的 JSON 对象列表

[英]How to decode nested JSON List of Objects in Dart/Flutter

I'm trying to figure out how I can decode the following JSON in Flutter.我试图弄清楚如何在 Flutter 中解码以下 JSON。

https://covid.ourworldindata.org/data/owid-covid-data.json https://covid.ourworldindata.org/data/owid-covid-data.json

I tried the following structure, but it doesn't work.我尝试了以下结构,但它不起作用。

@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);
}

Use Map to convert dynamic to String .使用 Map 将dynamic转换为String Directly assigning List to List will throw an error.直接将 List 分配给 List 会抛出错误。 You have create getters yourself.您自己创建了吸气剂。

Consider this example:考虑这个例子:

(jsonDecode(response.body)["data"] as List).map((e) => e as Map<String, dynamic>)?.toList();

Now assign to an instance of the custom class you have made.现在分配给您创建的自定义 class 的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM