【问题标题】:Parse List<dynamic> using json_serializable library in Flutter在 Flutter 中使用 json_serializable 库解析 List<dynamic>
【发布时间】:2019-10-11 19:25:07
【问题描述】:

考虑以下 json:

[
 {
  "id": 1
  "name": "foo"
 },
 {
  "id": 1
  "name": "foo"
 }
]

我正在尝试使用 json_serializable 库来解析它。

json.decode(response.body) 返回List&lt;dynamic&gt;

但是 json_serializable 会自动生成 fromJsontoJson 类型为 Map&lt;String, dynamic json&gt; 的方法。

在 json_serializable 中有什么方法可以解析List&lt;dynamic&gt;使用自动生成的方法而不是手动

【问题讨论】:

  • 您找到答案了吗?我也想使用生成可序列化的工厂方法来做到这一点

标签: flutter flutter-dependencies json-serialization


【解决方案1】:

你应该这样试试;

@JsonSerializable()
class Example{
    int id; String name;
    Example({this.id, this.name})
}

调用您的 Future 函数并将其保存在变量 {parsed} 中,然后通过执行以下操作将映射的数据转换为列表:

List<Example> result = parsed.map((i) => Example.fromJson(i)).toList();

【讨论】:

  • 为什么你的结果有Example 类型?应该是List&lt;Example&gt;
  • 不,你颠倒了这些地方。 List&lt;Example&gt; result = parsed.map((i) =&gt; Example.fromJson(i)).toList(); 是正确的
猜你喜欢
  • 2021-09-01
  • 2021-12-23
  • 2020-11-12
  • 2021-11-17
  • 2021-05-27
  • 2023-03-09
  • 1970-01-01
  • 2018-12-01
  • 2020-10-03
相关资源
最近更新 更多