1

I have array of country json objects like this

[{"id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg"},
        {"id":8,"name":"Albania","alpha2":"al","alpha3":"alb"},
        {"id":12,"name":"Algeria","alpha2":"dz","alpha3":"dza"},..

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

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

Can anyone explain how to do this conversion ?

2 Answers 2

1

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.

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

Comments

0

I use this straight forward way:

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

myTestModel=(json.decode(response.body) as List).map((i) =>
              TestModel.fromJson(i)).toList();

The link can be really helpful: json_serializable

4 Comments

can you explain TestModel.fromJson method?
fromJson is a Function of json_annotation which is used in decoding the assosiated JSON value to the annotated field.
and TestModel is the same class as your Country class which has fields
and if you want to learn more about how to parse complex json you can have a look at this article. :) medium.com/flutter-community/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.