简体   繁体   中英

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.

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 . Directly assigning List to List will throw an error. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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