在将 json 转换为 Dart 中的对象列表时,如何避免如此多的转换和映射?

云风月太阳

在 Dart (Flutter) 中,我想从创建类似于此的 json 的 api 端点创建一个“货币”对象列表:

{
 "AED": "United Arab Emirates Dirham",
 "AFN": "Afghan Afghani",
 "ALL": "Albanian Lek",
 "AMD": "Armenian Dram",
 "ANG": "Netherlands Antillean Guilder",
 ...
 ...
}

我的“货币”课程很简单:

class Currency {
  String code;
  String fullName;
  Currency(this.code, this.fullName);
}

我使用以下方法获取 Json 格式的列表货币,然后创建货币对象列表:

Future<List<Currency>> getCurrencies() async {
   final http.Client client = http.Client();
   final String uri = "https://openexchangerates.org/api/currencies.json";
   return await client
    .get(uri)
    .then((response) 
      {
        var jsonEntries = (json.decode(response.body) as Map<String, dynamic>).entries.toList();
        var currencyEntries = jsonEntries.map((x) => new Currency(x.key, "", x.value));
        return currencyEntries.toList();
      })
    .catchError((e) => print(e))
    .whenComplete(() => client.close());
}

必须有更有效的方法来做到这一点。我必须做很多映射、转换、toListing 才能从这个简单的 Json 字符串创建对象。

我怎样才能以更短、更有效的方式实现这一目标?

内特·博斯

您可能想研究像json_serializable. 从 JSON 获取强类型对象的强制转换和映射的必要性是一个已知的痛点,但目前在语言级别没有解决方案。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章