Flutter解析JSON报错Expected a value of type 'Iterable' but got '_JsonMap'求助
错误原因
- 根JSON结构为对象(Map类型),你直接遍历根对象触发类型不匹配:你需要的数组存储在根对象的
inspections字段下,需先取出该字段再遍历。 Inspection.fromJson方法存在未处理的类型转换问题:JSON中state、interval为字符串格式,date为dd.MM.yyyy格式的字符串,无法直接赋值给int、DateTime类型的类属性。
修复方案
1. 修改解析函数
Future <List<Inspection>> FutureInspections() async { var inspections = <Inspection>[]; final String response = await rootBundle.loadString('assets/sample.json'); // 解码后先转成Map类型获取根对象 Map<String, dynamic> rootJson = json.decode(response); // 取出inspections字段对应的数组再遍历 List<dynamic> inspectionsJson = rootJson['inspections']; for (var inspectionJson in inspectionsJson) { inspections.add(Inspection.fromJson(inspectionJson)); } return inspections; }
2. 修复Inspection.fromJson类型转换逻辑
Inspection.fromJson(Map<String, dynamic>json){ _description=json['description']; // 字符串转int _interval=int.parse(json['interval']); _state=int.parse(json['state']); // 解析dd.MM.yyyy格式的日期字符串为DateTime List<String> dateSegments = json['date'].split('.'); _date = DateTime(int.parse(dateSegments[2]), int.parse(dateSegments[1]), int.parse(dateSegments[0])); }
内容的提问来源于stack exchange,提问作者MCB
相关产品推荐
相关产品推荐

