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

Flutter解析嵌套JSON的Dart Model类报类型不匹配错误如何修复

问题原因
  • 核心错误为User类的字段类型定义与JSON结构不匹配:你将route、distributor两个字段声明为String类型,但JSON中这两个字段都是嵌套对象,Dart解析时无法将Map类型强制转为String,因此抛出类型不匹配异常。
修正后的完整代码
import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  User({
    this.visitDate,
    this.route,
    this.distributor,
  });

  // 修正字段类型,适配空安全与嵌套结构
  String? visitDate;
  Route? route;
  Distributor? distributor;

  factory User.fromJson(Map<String, dynamic> json) => User(
    visitDate: json["visitDate"],
    // 嵌套解析对应对象
    route: json["route"] == null ? null : Route.fromJson(json["route"]),
    distributor: json["distributor"] == null ? null : Distributor.fromJson(json["distributor"]),
  );

  Map<String, dynamic> toJson() => {
    "visitDate": visitDate,
    // 序列化时调用对应对象的toJson方法
    "route": route?.toJson(),
    "distributor": distributor?.toJson(),
  };
}

class Route {
  Route({
    this.routeID,
    this.routeTitle,
  });

  String? routeID;
  String? routeTitle;

  factory Route.fromJson(Map<String, dynamic> json) => Route(
    routeID: json["routeID"],
    routeTitle: json["routeTitle"],
  );

  Map<String, dynamic> toJson() => {
    "routeID": routeID,
    "routeTitle": routeTitle,
  };
}

class Distributor {
  Distributor({
    this.distributorID,
    this.distributorName,
  });

  String? distributorID;
  String? distributorName;

  factory Distributor.fromJson(Map<String, dynamic> json) => Distributor(
    distributorID: json["distributorID"],
    distributorName: json["distributorName"],
  );

  Map<String, dynamic> toJson() => {
    "distributorID": distributorID,
    "distributorName": distributorName,
  };
}
额外建议
  • 复杂JSON场景下推荐使用官方的json_serializable库自动生成Model解析代码,无需手写,可完全避免此类类型匹配错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:06