How would I parse a nested array of objects such as the one below.
{
"status": "success",
"code": 200,
"message": "The request was successful",
"data": [
{
"name": "Abu Dhabi",
"id": 4139,
"parent": 5153,
"type": "city",
"imageURL": ""
},
{
"name": "Croatia",
"id": 5037,
"parent": 6886,
"type": "country",
"imageURL": ""
},
]
}
I am currently making an API call which returns data in the format as shown above.
My api call is as follows:
Future<Location> getLocations() async {
final response =
await http.get('$endpoint/locations', headers: authenticatedHeader);
if (response.statusCode == 200) {
final responseJson = json.decode(response.body);
// If server returns an OK response, parse the JSON.
return Location.fromJson(responseJson);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
I then have a location class as below:
class Location {
String name;
int id;
int parent;
String type;
String imageURL;
Location(
{this.name, this.id, this.parent, this.type, this.imageURL});
factory Location.fromJson(Map<String, dynamic> json) =>
_locationFromJson(json);
}
Location _locationFromJson(Map<String, dynamic> json) {
return Location(
name: json['name'] as String,
id: json['id'] as int,
parent: json['parent'] as int,
type: json['type'] as String,
imageURL: json['imageURL'] as String
);
}
I am hoping to be able to retrieve all the locations above using a listview builder and create a listtile for each location.
How can I parse the JSON correctly?
return Location.fromJson(responseJson.data);