Flutter中Exercise类JSON反序列化出现类型不匹配异常的问题求助
解决Flutter JSON反序列化中List类型不匹配的问题
这个错误type 'List' is not a subtype of type 'List<int>'本质是Dart强类型机制导致的典型问题:JSON解析后返回的json['equipmentIds']是List<dynamic>类型,而你的equipmentIds字段声明为List<int>,Dart无法自动完成这种隐式类型转换——如果JSON数组里的元素还不是纯数字(比如是字符串形式的数字),就会直接触发这个异常。
解决方案
根据你的JSON数据实际格式,选择对应的修复方式:
情况1:JSON中的equipmentIds是数字数组(比如[1, 2, 3])
直接将List<dynamic>显式转换为List<int>,修改fromJson构造函数:
Exercise.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], equipmentIds = List<int>.from(json['equipmentIds']);
情况2:JSON中的equipmentIds是字符串数组(比如["1", "2", "3"])
需要先把每个字符串元素解析为int,再转为List:
Exercise.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], equipmentIds = (json['equipmentIds'] as List<dynamic>) .map((e) => int.parse(e.toString())) .toList();
完整修改后的Exercise类
class Exercise { int id; String name; List<int> equipmentIds; Exercise(this.id, this.name, this.equipmentIds); Exercise.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], // 二选一,根据你的JSON实际格式调整 equipmentIds = List<int>.from(json['equipmentIds']); // equipmentIds = (json['equipmentIds'] as List<dynamic>).map((e) => int.parse(e.toString())).toList(); Map<String, dynamic> toJson() => { 'id': id, 'name': name, 'equipmentIds': equipmentIds, }; }
额外优化建议
如果不确定JSON里的元素类型,可以加个类型检查避免崩溃,比如:
equipmentIds: (json['equipmentIds'] as List<dynamic>) .where((e) => e is int || (e is String && int.tryParse(e) != null)) .map((e) => e is int ? e : int.parse(e.toString())) .toList();
内容的提问来源于stack exchange,提问作者Franz
相关产品推荐
相关产品推荐

