You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter解析JSON报错Expected a value of type 'Iterable' but got '_JsonMap'求助

错误原因

  1. 根JSON结构为对象(Map类型),你直接遍历根对象触发类型不匹配:你需要的数组存储在根对象的inspections字段下,需先取出该字段再遍历。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:06:04