1

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?

2
  • I mean, it is just JSON, so realistically, make something serializable. Commented Dec 26, 2018 at 1:45
  • I would recommend using built_value libraries. It is easy and powerful. pub.dartlang.org/packages/built_value Commented Dec 26, 2018 at 3:19

1 Answer 1

2

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}"));
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.