【问题标题】:JSON associative array to Dart/Flutter objectJSON 关联数组到 Dart/Flutter 对象
【发布时间】:2019-05-24 09:37:34
【问题描述】:

我有以下对象结构的 JSON 响应:

{
"cities": {
    "5": {
        "id": "5",
        "name": "New York"
    },
    "6": {
        "id": "6",
        "name": "Los Angeles"
    }
},
"total": 2,
"page": 1,
"total_pages": 1
}

如您所见,“城市”显然是一个关联类型数组,列出了所有被引用的城市。我正在尝试创建一个 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 对象,但我不确定它是如何工作的?

【问题讨论】:

  • 我的意思是,它只是 JSON,所以实际上,做一些可序列化的东西。
  • 我会推荐使用 built_value 库。它简单而强大。 pub.dartlang.org/packages/built_value

标签: json dart flutter


【解决方案1】:

你必须修复你的 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}"));

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2019-12-21
    • 1970-01-01
    • 2016-01-11
    • 2013-09-27
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多