json - 在将 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 字符串创建对象。
我怎样才能以更短、更有效的方式实现这一目标?
解决方案
您可能想要研究代码生成方法,例如json_serializable
. 强制转换和映射以从 JSON 获取强类型对象的必要性是一个已知的痛点,但目前在语言级别没有解决方案。
推荐阅读
- html - 应用 CSS 变换比例而不移动其他元素
- nestjs - Prisma 客户端类型系统创建与服务方法的强耦合
- google-sheets - 如何使用 Google Doc 获取实时报价?
- logging - 我们如何从日志中获取哨兵实体,我们对实体的 KQL 查询是什么,哨兵 ID 信息
- sql - BigQuery 中的多个联合自联接
- python - ValueError:对已关闭文件的 I/O 操作,flush()
- sql - 我有一个 Sql 表中日期之间的差异总和。如何计算以天、小时、分钟为单位的平均值?
- go - go-git 从轻量级标签中获取树
- html - 应用 z-index 时,非嵌套 div 是否算作兄弟?
- mysql - 无法安装 MySQL