首页 > 解决方案 > 在将 json 转换为 Dart 中的对象列表时如何避免这么多的转换和映射?

问题描述

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

{
 "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 字符串创建对象。

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

标签: jsonlistdart

解决方案


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


推荐阅读