【问题标题】:How to decode nested JSON List of Objects in Dart/Flutter如何在 Dart/Flutter 中解码嵌套的 JSON 对象列表
【发布时间】:2021-05-13 15:57:26
【问题描述】:

我正在尝试弄清楚如何在 Flutter 中解码以下 JSON。

https://covid.ourworldindata.org/data/owid-covid-data.json

我尝试了以下结构,但它不起作用。

@JsonSerializable()
class StatisticsResponse {
  Map<String, Country> data;
  //List<Country> data;
  StatisticsResponse({this.data});

  factory StatisticsResponse.fromJson(Map<String, dynamic> json) =>
      _$StatisticsResponseFromJson(json);
}

@JsonSerializable()
class Country {
  String continent;
  String location;
  int population;
  //Map<String, Data> data;
  List<Data> data;

  Country({this.continent, this.location, this.population, this.data
  });

  factory Country.fromJson(Map<String, dynamic> json) =>
      _$CountryFromJson(json);
}

【问题讨论】:

标签: json flutter dart


【解决方案1】:

使用 Map 将dynamic 转换为String。直接将 List 分配给 List 会抛出错误。您自己创建了吸气剂。

考虑这个例子:

(jsonDecode(response.body)["data"] as List).map((e) =&gt; e as Map&lt;String, dynamic&gt;)?.toList();

现在分配给您创建的自定义类的实例。

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 2023-04-02
    • 2023-01-14
    • 2020-05-02
    • 2022-01-09
    • 2020-05-21
    • 2020-06-17
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多