0

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);
}
3
  • Would you please elaborate on what "does not work" mean? Commented Feb 9, 2021 at 23:57
  • stackoverflow.com/questions/57662221/… Commented Feb 10, 2021 at 4:56
  • There is not a runtime error. The field StatisticsResponse.data is just NULL Commented Feb 10, 2021 at 9:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.