【问题标题】:How to decode JSON to list of model objects如何将 JSON 解码为模型对象列表
【发布时间】:2019-07-06 13:38:33
【问题描述】:

我正在使用下面的代码解码一个 JSON http 响应模型对象列表。它工作得很好,但是我问我如何将代码重写为

  1. 不使用类型转换“作为列表”
  2. 将类型“动态”替换为更具体的类型“代码模型”
final List<CodeModel> codes = (json.decode(response.body) as List)
  .map((dynamic model) => CodeModel.fromJson(model))
  .toList();

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    一般来说,您应该避免公开的静态类型,因为分析器可以为您找出答案。

    您可以将代码替换为:

      final codes =
          json.decode(response.body).map<CodeModel>((m) => CodeModel.fromJson(m)).toList();
    
      print(codes.runtimeType);
    

    codes 的类型无需指定 - 可以推断。

    .map 更改为 .map&lt;CodeModel&gt; 告诉分析器 lambda 将返回 CodeModel,因此 toList 将生成它们的列表。

    打印行按预期打印List&lt;CodeModel&gt;

    【讨论】:

    • 感谢您的帮助,这完全符合预期!
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多