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

Flutter/Dart解析JSON报错List<dynamic>不是Map<String,dynamic>子类型如何解决

问题原因

  • 服务端返回的响应外层是[]包裹的JSON数组,你直接把全量解码结果传给入参要求为Map<String, dynamic>的ProductModel.fromJson方法,触发类型不匹配报错
  • ProductModel中定义的图片字段名为image,但服务端返回的对应字段名为images,字段名不匹配会导致取值为空
  • 拿到图片数组后没有做类型映射,直接把List<dynamic>赋值给List<ImageModel>类型的字段,也会触发类型错误
  • 额外问题:ProductModel的toJson方法存在笔误,regular_rice应为regular_price

修正方案

1. 调整请求逻辑代码

if (response.statusCode == 200) {
  setState(() {
    var bodybytedecoded= jsonDecode(utf8.decode(response.bodyBytes)) as List;
    // 遍历数组映射为产品模型列表
    final List<ProductModel> productList = bodybytedecoded.map((item) => ProductModel.fromJson(item as Map<String,dynamic>)).toList();
    print(productList);
    // 后续使用productList渲染即可
  });
} else {
  print(response.reasonPhrase);
}

2. 调整模型类代码

class ProductModel{
  final int id;
  final String name;
  final String regular_price;
  final String description;
  final List<ImageModel> image;

  ProductModel({
    required this.id,
    required this.name,
    required this.regular_price,
    required this.description,
    required this.image
  });

  factory ProductModel.fromJson(Map<String,dynamic> json){
    final name = json["name"] as String;
    final id = json["id"] as int;
    final regular_price = json["regular_price"] as String;
    final description = json["description"] as String;
    // 映射图片数组为ImageModel列表
    final image = (json["images"] as List).map((img) => ImageModel.fromJson(img as Map<String,dynamic>)).toList();
    return ProductModel(
      id: id,
      name: name,
      regular_price: regular_price,
      description: description,
      image: image
    );
  }

  Map<String,dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data["id"] = id;
    data["name"] = name;
    // 修正笔误
    data["regular_price"] = regular_price;
    data["description"] = description;
    data["image"] = image.map((img) => img.toJson()).toList();
    return data;
  }
}

class ImageModel{
  final String src;
  ImageModel({required this.src});
  factory ImageModel.fromJson(Map<String,dynamic> json ){
    return ImageModel(src:  json["src"] as String);
  }

  Map<String,dynamic> toJson() {
    return <String, dynamic>{
      "src": src
    };
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:03