Flutter JSON解析错误:List无法转为Map<String, dynamic>求助
解决Flutter JSON解析错误:
type 'List' is not a subtype of type 'Map<String, dynamic>' 核心问题有两个:
- JSON中的
test是数组(List),但你代码里将其当作单个Map解析,且test字段定义为单个MonthWiseTests对象,类型完全不匹配 MonthWiseTests.fromJson的写法错误,它当前逻辑是取Map的第一个key作为month,但JSON里每个test项是明确包含month和tests字段的Map
以下是完整修正方案:
1. 修正TestHistoryEntity的字段与解析逻辑
将test字段从单个对象改为列表,同时遍历JSON数组生成对应对象列表:
class TestHistoryEntity { TestHistoryEntity({this.subjects, this.test, this.filter1}); TestHistoryEntity.fromJson(Map<String, dynamic> json) { if (json['subjects'] != null) { subjects = <Subjects>[]; (json['subjects'] as List).forEach((v) { subjects!.add(Subjects.fromJson(v as Map<String, dynamic>)); }); } if (json['filter1'] != null) { filter1 = <String>[]; (json['filter1'] as List).forEach((v) { filter1!.add(v.toString()); }); } if (kDebugMode) { print("FILTER_TEST"); print(filter1); } // 修复test数组解析逻辑 if (json['test'] != null) { test = <MonthWiseTests>[]; (json['test'] as List).forEach((v) { test!.add(MonthWiseTests.fromJson(v as Map<String, dynamic>)); }); } } List<Subjects>? subjects; // 将单个对象改为列表,匹配JSON结构 List<MonthWiseTests>? test; List<String>? filter1; // 修复toJson方法(若需要序列化) Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (subjects != null) { data['subjects'] = subjects!.map((v) => v.toJson()).toList(); } if (test != null) { data['test'] = test!.map((v) => v.toJson()).toList(); } if (filter1 != null) { data['filter1'] = filter1; } return data; } }
2. 修正MonthWiseTests的fromJson方法
原来的解析逻辑完全不符合JSON结构,直接读取map['month']和map['tests']字段即可:
class MonthWiseTests { MonthWiseTests({ this.month, this.tests, }); factory MonthWiseTests.fromJson(Map<String, dynamic> map) { return MonthWiseTests( // 直接读取JSON中的month字段 month: map['month'] as String?, // 解析tests数组,并过滤可能的null值 tests: map['tests'] != null ? List<Test>.from( (map['tests'] as List<dynamic>).map<Test?>( (x) => Test.fromJson(x as Map<String, dynamic>), ).whereType<Test>(), ) : null, ); } String? month; List<Test>? tests; MonthWiseTests copyWith({ String? month, List<Test>? tests, }) { return MonthWiseTests( month: month ?? this.month, tests: tests ?? this.tests, ); } Map<String, dynamic> toJson() { return <String, dynamic>{ 'month': month, 'tests': tests?.map((x) => x.toJson()).toList(), }; } }
改动说明
- 字段类型对齐:JSON中
test是数组,所以TestHistoryEntity的test字段必须定义为List<MonthWiseTests>?,而非单个对象 - 解析逻辑对齐:遍历
json['test']数组,将每个元素(Map类型)传入MonthWiseTests.fromJson生成对象 - 修复MonthWiseTests解析逻辑:去掉错误的
map.keys.first逻辑,直接读取JSON中明确的month和tests字段,同时添加whereType<Test>()过滤可能的null值,避免列表中出现空元素
内容的提问来源于stack exchange,提问作者hobik
相关产品推荐
相关产品推荐

