如何修复Dart项目main.dart中CovidTodayResult相关JSON序列化代码报错
报错修复方案
以下是你提供的序列化代码的常见问题及对应修复方案:
- 问题1:
json.decode(str)后的返回值类型未做校验,直接调用map会触发类型错误
修复:先判断解码后的数据是否为List类型,再执行后续转换
修正后的反序列化代码:List<CovidTodayResult> covidTodayResultFromJson(String str) { final decoded = json.decode(str); if (decoded is List) { return decoded.map((x) => CovidTodayResult.fromJson(x as Map<String, dynamic>)).toList(); } throw FormatException('Expected a list of CovidTodayResult data'); } - 问题2:空安全适配问题,若接口返回的列表可能存在空元素,需要增加空判断避免空引用异常
修复:在map转换时过滤空值
示例代码:List<CovidTodayResult> covidTodayResultFromJson(String str) { final decoded = json.decode(str); if (decoded is List) { return decoded .where((x) => x != null) .map((x) => CovidTodayResult.fromJson(x as Map<String, dynamic>)) .toList(); } throw FormatException('Expected a list of CovidTodayResult data'); } - 问题3:如果你的报错为
The argument type 'Iterable<CovidTodayResult>' can't be assigned to the parameter type 'Iterable<dynamic>'这类类型不匹配错误,是因为Dart新版本中List.from的入参类型校验更严格,直接用toList()替代即可,不需要额外套List.from
对应的序列化代码可简化为:String covidTodayResultToJson(List<CovidTodayResult> data) => json.encode(data.map((x) => x.toJson()).toList());
若以上方案未解决问题,可检查CovidTodayResult.fromJson方法内的字段是否和接口返回的字段完全匹配,是否存在字段类型不对应、缺失必填字段的情况。
内容的提问来源于stack exchange,提问作者Peem
相关产品推荐
相关产品推荐

