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

Flutter中二维嵌套List含两种数据类型时如何创建对应类Model

解决方案

核心修改点有两个:调整value字段的类型定义、修改嵌套数组的解析逻辑,完整修改后的代码如下:

@JsonSerializable()
class GetReportBodyData {
  String type;
  String title;
  List<String> headers;
  // 原类型是List<List<int>>,替换为List<List<Object>>,兼容String和int两种类型
  List<List<Object>> value = [];

  GetReportBodyData({this.type, this.title, this.headers, this.value});

  @override
  String toString() {
    return 'GetReportBodyData{type: $type, title: $title, header: $headers, value: $value}';
  }

  factory GetReportBodyData.fromJson(Map<String, dynamic> json) {
    // 逐层解析二维数组,先转外层List,再转每一个内层List
    var valueJson = json["value"] as List;
    var parsedValue = valueJson.map((innerList) => List<Object>.from(innerList)).toList();
    return GetReportBodyData(
        type: json["type"],
        title: json["title"],
        headers: json["header"] != null ? List<String>.from(json["header"]) :[],
        value: parsedValue
    );
  }

  Map<String, dynamic>toJson() => {
    "type": type,
    "title": title,
    "header": headers,
    "value": value
  };
}

补充说明

  • 如果你不确定后续接口返回的内层数组会不会有其他类型(比如布尔值、浮点数),可以把List<List<Object>>替换为List<List<dynamic>>,灵活性更高但会丢失部分类型校验能力。
  • 后续从value数组里取值时,判断类型后再使用即可,示例:
    // 取第一个内层数组的第一个值(水果名称)
    String fruitName = value[0][0] as String;
    // 取第一个内层数组的第三个值(数字)
    int count = value[0][2] as int;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:18:01