我有具有以下对象结构的 JSON 响应:
{
"cities": {
"5": {
"id": "5",
"name": "New York"
},
"6": {
"id": "6",
"name": "Los Angeles"
}
},
"total": 2,
"page": 1,
"total_pages": 1
}
如您所见,“cities”显然是一个关联类型数组,列出了所有被引用的城市。我正在尝试创建一个 Dart 对象,它可以从 JSON 对象中保存这些城市值。 城市对象非常简单:
class City {
int id;
String name;
City(this.id, this.name);
City.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
}
但是,我不确定如何创建 CityResults 对象。我通常从 json 数组创建一个 List 对象,但我不确定这将如何工作?
最佳答案
你必须修复你的 City
类,因为你来自 json 的 'id' 是字符串,所以你有两个选择:
1- 用字符串替换 int
class City {
String id;
或
2-更改fromJson
方法
City.fromJson(Map<String, dynamic> json) {
id = int.parse(json['id']);
name = json['name'];
}
最后,这可能是您的解析方法:
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}"));
关于JSON 关联数组到 Dart/Flutter 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926715/