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

Flutter/Dart解析嵌套JSON时遇到'type 'Model' is not a subtype of type List<dynamic>'错误的解决方法

解决Flutter/Dart嵌套JSON解析的类型转换错误

咱们先把你代码里的两个关键问题修正掉,就能解决这个类型转换报错了:

1. 修正Model类的构造函数命名笔误

你的Model类里把构造函数写成了Lineup,这明显是手滑写错了,得改成和类名一致的Model:

class Model { 
  final String key1; 
  final String key2; 
  // 把Lineup改为Model,和类名保持一致
  const Model({ required this.key1, required this.key2 }); 
  factory Model.fromJson(Map<String, dynamic> json) { 
    return Model( 
      key1: json['key1'] as String, 
      key2: json['key2'] as String 
    ); 
  } 
}

2. 修复ModelResponse中array1的类型转换逻辑

你遇到的type 'Model' is not a subtype of type List<dynamic>错误,核心原因是把as List的位置放错了,还多了不必要的类型强转。正确的逻辑应该是:先把json['array1']强制转为List类型,再遍历列表里的每个元素,调用Model.fromJson解析成Model对象。

修正后的ModelResponse类:

class ModelResponse { 
  final List<Model> array1; 
  final List<Model> array2; 
  const ModelResponse({ required this.array1, required this.array2 }); 
  factory ModelResponse.fromJson(Map<String, dynamic> json) { 
    return ModelResponse( 
      // 先将json['array1']转为List,再逐个解析元素
      array1: (json['array1'] as List)
        .map((i) => Model.fromJson(i as Map<String, dynamic>))
        .toList(), 
      array2: (json['array2'] as List) 
        .map((i) => Model.fromJson(i as Map<String, dynamic>)) 
        .toList() 
    ); 
  } 
}

额外小优化:增强类型安全

我在上面的代码里给i也加了as Map<String, dynamic>的强转,这样如果JSON结构不符合预期,错误会更早暴露,代码的可读性也更强,适合新手排查问题。

你的调用逻辑是正确的

最后确认下,你解析外层JSON的代码没问题:

var jsonResponse = jsonDecode(response.body); 
return ModelResponse.fromJson(jsonResponse['item']);

因为服务器返回的最外层是{"item": ...},所以取jsonResponse['item']正好是ModelResponse需要的Map结构。

这样修改后,就能正常解析嵌套的JSON数据,不会再出现类型转换的报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:07:44