【发布时间】:2019-12-21 19:57:27
【问题描述】:
我将如何解析嵌套的对象数组,例如下面的对象。
{
"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": ""
},
]
}
我目前正在进行 API 调用,它以如上所示的格式返回数据。
我的api调用如下:
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');
}
}
然后我有一个如下位置类:
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
);
}
我希望能够使用 listview builder 检索上述所有位置,并为每个位置创建一个 listtile。
如何正确解析 JSON?
【问题讨论】:
-
return Location.fromJson(responseJson.data);
标签: arrays json object flutter