ajacian81
ajacian81

Reputation: 7579

JSON associative array to Dart/Flutter object

I have JSON response with the following object structure:

{
"cities": {
    "5": {
        "id": "5",
        "name": "New York"
    },
    "6": {
        "id": "6",
        "name": "Los Angeles"
    }
},
"total": 2,
"page": 1,
"total_pages": 1
}

As you can see, "cities" is clearly an associative type array that is listing all the cities being referenced. I'm trying to create a Dart object that can hold these cities values from a JSON object. The city object is pretty straightforward:

class City {
  int id;
  String name;
  City(this.id, this.name);
  City.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }
}

however, I'm not sure how to create the CityResults object. I usually create a List object from json arrays but I'm not sure how this would work?

Upvotes: 1

Views: 5715

Answers (1)

diegoveloper
diegoveloper

Reputation: 103531

You have to fix your City class, because your 'id' from json is String, so you have two options:

1- Replace int by String

class City {
 String id;

or

2- Change the fromJson method

City.fromJson(Map<String, dynamic> json) {
    id = int.parse(json['id']);
    name = json['name'];
  }   

Finally, this could be your parse method :

         final Map cityResponse = json.decode(data)["cities"];
            final List<City> cities = cityResponse.values
                .map((jsonValue) => City.fromJson(jsonValue))
                .toList();

            //now you have the list of your cities inside cities variable.    
            cities.forEach((city) => print("City: ${city.id} , ${city.name}"));

Upvotes: 2

Related Questions