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

Dart/Flutter解析JSON报错:'String'不是'Iterable'子类型

Dart/Flutter JSON解析错误:String无法转换为Iterable

错误信息

错误:类型 'String' 不是类型 'Iterable' 的子类型,无法强制转换(原错误信息:Errore: type 'String' is not a subtype of type 'Iterable' in type cast)

我的代码

Map value = await apiRequestMap('/api/Recipes/' + model, {}, UrlRequest.GET, true, false, true);
String decodeMapOperation = json.encode(value);
(decodeMapOperation as Iterable<dynamic>) // 此处抛出错误
    .map((dynamic jsonObject) => print(jsonObject['name']))
    .toList();

接口返回的JSON数据

[
    {
        "id": 2,
        "name": "波伦亚酱",
        "tool": "",
        "description": "",
        "link": "",
        "picture": "http://207.154.221.255:8600/pictures/recipes/Salsa Bolognese.jpg",
        "phases": [
            {
                "Set_Rpm1_Utensile": "0",
                "Set_Rpm2_Utensile": "0",
                "On_Rpm_Utensile": "0",
                "Off_Rpm_Utensile": "0",
                "Tempo_Rpm_Utensile": "0",
                "Set_Vuoto": "0",
                "On_Vuoto": "0",
                "Off_Vuoto": "0",
                "Tempo_Vuoto": "0",
                "Set_Pressione_In": "0",
                "Set_Pressione_Out": "0",
                "Spatola_On": "false",
                "N_Rotazioni_Spatola": "0",
                "Pausa_Spatola": "0",
                "Set_Caldo": "0",
                "Set_Vapore_Diretto": "0",
                "On_Caldo": "0",
                "Off_Caldo": "0",
                "Tempo_Caldo": "0",
                "Set_Freddo": "0",
                "Set_Gelida": "0",
                "On_Freddo": "0",
                "Off_Freddo": "0",
                "Tempo_Freddo": "0"
            }
        ],
        "time": 12,
        "instructions": [
            {
                "id": 1,
                "content": "将所有食材放入Qbo",
                "order": 1,
                "recipeId": 2
            },
            {
                "id": 2,
                "content": "盖上盖子",
                "order": 2,
                "recipeId": 2
            },
            {
                "id": 3,
                "content": "将容器倾斜至2级并启动程序",
                "order": 3,
                "recipeId": 2
            },
            {
                "id": 4,
                "content": "加压煮酱(第2和第3阶段)",
                "order": 4,
                "recipeId": 2
            },
            {
                "id": 5,
                "content": "蒸发多余的液体(第4阶段)",
                "order": 5,
                "recipeId": 2
            },
            {
                "id": 6,
                "content": "将容器调平,打开阀门恢复压力",
                "order": 6,
                "recipeId": 2
            },
            {
                "id": 7,
                "content": "取出成品",
                "order": 7,
                "recipeId": 2
            }
        ],
        "ingredients": [
            {
                "id": 1,
                "name": "牛肉末",
                "quantity": "650克",
                "recipeId": 2
            },
            {
                "id": 2,
                "name": "猪肉末",
                "quantity": "450克",
                "recipeId": 2
            },
            {
                "id": 3,
                "name": "切碎的培根",
                "quantity": "450克",
                "recipeId": 2
            },
            {
                "id": 4,
                "name": "炒香的蔬菜碎",
                "quantity": "600克",
                "recipeId": 2
            },
            {
                "id": 5,
                "name": "三倍浓缩番茄酱",
                "quantity": "225克",
                "recipeId": 2
            },
            {
                "id": 6,
                "name": "白葡萄酒",
                "quantity": "100克",
                "recipeId": 2
            },
            {
                "id": 7,
                "name": "盐",
                "quantity": "12克",
                "recipeId": 2
            },
            {
                "id": 8,
                "name": "胡椒",
                "quantity": "3克",
                "recipeId": 2
            },
            {
                "id": 9,
                "name": "月桂叶1片",
                "quantity": "1",
                "recipeId": 2
            },
            {
                "id": 10,
                "name": "肉豆蔻",
                "quantity": "1",
                "recipeId": 2
            }
        ],
        "updatedAt": "2023-10-09T14:39:18.661132Z"
    }
]

问题原因与修复方案

核心问题

  1. 逻辑完全颠倒:你把已经解析好的Map用json.encode()转成了JSON字符串,然后试图把这个字符串强转为Iterable——字符串本质是字符序列,不可能是你需要的数组/集合类型,必然报错。
  2. 返回值类型不匹配:接口返回的是JSON数组(外层是[]),但你用Map接收,类型不匹配会导致后续处理全部出错。

快速修复代码

步骤1:修正返回值类型

将接收变量类型改为List<dynamic>,匹配接口返回的数组结构:

List<dynamic> value = await apiRequestMap('/api/Recipes/' + model, {}, UrlRequest.GET, true, false, true);

步骤2:直接遍历解析后的集合

不需要再做json.encode(),因为apiRequestMap已经完成了解析工作,直接遍历集合即可:

value.map((jsonObject) => print(jsonObject['name'])).toList();

完整修复代码

List<dynamic> value = await apiRequestMap('/api/Recipes/' + model, {}, UrlRequest.GET, true, false, true);
value.map((jsonObject) => print(jsonObject['name'])).toList();

进阶:类型安全的实体类解析(推荐)

为了避免后续的类型错误,建议创建实体类来封装数据:

class Recipe {
  final int id;
  final String name;
  final String tool;
  final String description;
  final String link;
  final String picture;
  final List<Phase> phases;
  final int time;
  final List<Instruction> instructions;
  final List<Ingredient> ingredients;
  final DateTime updatedAt;

  Recipe({
    required this.id,
    required this.name,
    required this.tool,
    required this.description,
    required this.link,
    required this.picture,
    required this.phases,
    required this.time,
    required this.instructions,
    required this.ingredients,
    required this.updatedAt,
  });

  factory Recipe.fromJson(Map<String, dynamic> json) {
    return Recipe(
      id: json['id'],
      name: json['name'],
      tool: json['tool'],
      description: json['description'],
      link: json['link'],
      picture: json['picture'],
      phases: (json['phases'] as List).map((p) => Phase.fromJson(p)).toList(),
      time: json['time'],
      instructions: (json['instructions'] as List).map((i) => Instruction.fromJson(i)).toList(),
      ingredients: (json['ingredients'] as List).map((i) => Ingredient.fromJson(i)).toList(),
      updatedAt: DateTime.parse(json['updatedAt']),
    );
  }
}

// 实现Phase类
class Phase {
  final String setRpm1Utensile;
  final String setRpm2Utensile;
  // ... 其他字段根据JSON结构补充

  Phase({
    required this.setRpm1Utensile,
    required this.setRpm2Utensile,
    // ... 其他字段
  });

  factory Phase.fromJson(Map<String, dynamic> json) {
    return Phase(
      setRpm1Utensile: json['Set_Rpm1_Utensile'],
      setRpm2Utensile: json['Set_Rpm2_Utensile'],
      // ... 其他字段赋值
    );
  }
}

// 同理实现Instruction和Ingredient类

使用实体类解析的代码:

List<Recipe> recipes = value.map((json) => Recipe.fromJson(json)).toList();
recipes.forEach((recipe) => print(recipe.name));

内容的提问来源于stack exchange,提问作者riki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:18:11