JSON 关联数组到 Dart/Flutter 对象

标签 json dart flutter

我有具有以下对象结构的 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/

相关文章:

json - 在 Swift 中获取 JSON

javascript - json.parse 在意外标记上失败,而其他解析器认为它是有效的

javascript - jQuery (JSONP) 的 JSON 问题

c# - Newtonsoft.JSON serializeobject 返回空 JSON 字符串

Flutter 和 Dart 尝试 catch——catch 不会触发

android - Flutter:无状态小组件中的 “Looking up a deactivated widget'祖先是不安全的

flutter - Flutter:通过Navigator.Push传递多个数据,然后将数据弹出

java - Flutter 原生 android 回调

dart - 路径 quadraticBezierTo : curve pass the control point

dart - 如何转换为 List<int> 到文件?