I have array of country json objects like this


I have got them to a map like this

Map<String, dynamic> jsonMap;
jsonMap = json.decode(jsonString);

After this I have the data like this

[{id: 4, name: Afghanistan, alpha2: af, alpha3: afg}, {id: 8, name: Albania, alpha2: al, alpha3: alb}, ...

What i want to do is create a List of county objects from this

int id;
String name;
String alpha2;
String alpha3;

Can anyone explain how to do this conversion ?

Solution 1: Maz341

I use this straight forward way:

List<TestModel> myTestModel;
var response = await http.get("myTestUrl");

myTestModel=(json.decode(response.body) as List).map((i) =>

The link can be really helpful: json_serializable

Solution 2: Darsh Shah

The best way to do it is to make a PODO out of this,

class Country {
  int id;
  String name;
  String alpha2;
  String alpha3;

  Country({this.id, this.name, this.alpha2, this.alpha3});

  Country.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    alpha2 = json['alpha2'];
    alpha3 = json['alpha3'];

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['alpha2'] = this.alpha2;
    data['alpha3'] = this.alpha3;
    return data;

Now using this you can access the fromJson method and also use the toJson method.