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

Flutter执行toJson时报错List<Tag>类型无法转为String如何解决

问题原因

你遇到的两次报错都是Dart处理自定义类列表序列化/反序列化时的典型类型不匹配问题,核心问题有两处:

  1. 序列化(toJson)阶段:Dart无法自动将List<Tag>、List<Pages>这类自定义类对象列表转换为可序列化的Map结构,直接赋值就会触发List<Tag>不是String类型的报错。你后续将列表强制转成toString()的操作是错误的,会导致字段变成字符串类型,反序列化时自然会触发String不能转为List<Tag>?的二次报错。
  2. 反序列化(fromJson)阶段:你直接将接口返回的tag_list、pages字段(本质是List<Map<String,dynamic>>类型)赋值给自定义类列表,没有做类型映射转换,这里本身也会触发类型不匹配错误。
修复方案

你只需要修改Diary类的fromJson和toJson方法,手动处理自定义类列表的类型转换即可,修改后的代码如下:

class Diary {
  String? title;
  String? location;
  String? address;
  List<Tag>? tagList;
  List<Pages>? pages;
  String? date;

  Diary({
    this.title,
    this.location,
    this.tagList,
    this.pages,
    this.date,
    this.address,
  });

  Diary.fromJson(Map<String, dynamic> json) {
    title = json['title'] ?? "";
    location = json['location'] ?? "";
    address = json["address"] ?? "";
    // 手动转换Tag列表
    tagList = json['tag_list'] != null 
        ? (json['tag_list'] as List).map((item) => Tag.fromJson(item)).toList() 
        : <Tag>[];
    // 手动转换Pages列表
    pages = json['pages'] != null 
        ? (json['pages'] as List).map((item) => Pages.fromJson(item)).toList() 
        : <Pages>[];
    date = json['date'] ?? '';
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['title'] = this.title;
    data['location'] = this.location;
    // 手动把Tag列表转成Map列表
    data['tag_list'] = this.tagList?.map((tag) => tag.toJson()).toList();
    // 手动把Pages列表转成Map列表
    data['pages'] = this.pages?.map((page) => page.toJson()).toList();
    data['date'] = this.date;
    data['address'] = this.address;
    return data;
  }
}
原理说明
  • 反序列化阶段:接口返回的列表字段默认是List<dynamic>类型,需要先强转为List,再遍历每个元素调用对应类的fromJson方法,转换为自定义类对象之后再组装成列表赋值。
  • 序列化阶段:需要遍历自定义类列表的每个元素,调用toJson方法转成Map类型,再组装成List<Map>结构,Dart才能正常识别序列化。

内容的提问来源于stack exchange,提问作者Choi yun seok

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:48:03