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

Flutter解析嵌套JSON接口响应调用报错的解决方案

Flutter嵌套JSON解析类型转换错误修复方案

问题根因

运行抛出类型转换错误的核心原因是接口返回的data字段为单个客户信息对象(Map类型),并非客户对象数组(List类型),原代码强行将map["data"]赋值给List<dynamic>类型变量,触发类型不匹配异常。

接口返回结构说明

当前POST接口返回的顶层结构共3个字段:

  • status:数字类型的接口状态码
  • message:字符串类型的接口返回提示
  • data:单条客户信息对象,不是数组结构

修复步骤

1. 实现正确的GetCustomer模型类

模型类的fromJson方法需要完全匹配接口返回的字段名(注意接口部分字段首字母大写、存在拼写误差),示例代码如下:

class GetCustomer {
  String? address;
  String? cityId;
  String? cityName;
  String? companyName;
  String? creditDays;
  String? customerId;
  String? email;
  String? gstNo;
  String? isApproved;
  String? lat;
  String? long;
  String? mobile;
  String? pincode;
  String? route;
  String? stateId;
  String? stateName;
  String? uniqueNumber;

  GetCustomer({
    this.address,
    this.cityId,
    this.cityName,
    this.companyName,
    this.creditDays,
    this.customerId,
    this.email,
    this.gstNo,
    this.isApproved,
    this.lat,
    this.long,
    this.mobile,
    this.pincode,
    this.route,
    this.stateId,
    this.stateName,
    this.uniqueNumber,
  });

  factory GetCustomer.fromJson(Map<String, dynamic> json) {
    return GetCustomer(
      address: json['Address'],
      cityId: json['CityID'],
      cityName: json['CityName'],
      companyName: json['CompanyName'],
      creditDays: json['CreditDays'],
      customerId: json['CusotmerID'],
      email: json['Email'],
      gstNo: json['GSTNo'],
      isApproved: json['IsApproved'],
      lat: json['Lat'],
      long: json['Long'],
      mobile: json['Mobile'],
      pincode: json['Pincode'],
      route: json['Route'],
      stateId: json['StateID'],
      stateName: json['StateName'],
      uniqueNumber: json['UniqueNumber'],
    );
  }
}

2. 修正JSON解析逻辑

去掉原代码中将data强转为List的错误写法,直接取出Map类型的data字段做解析即可,修复后的请求代码:

List<GetCustomer> customerList = [];

Future<List<GetCustomer>> getPostApi() async {
  final response = await http.post(
    Uri.parse('XYZ'),
    headers: {
      "Content-Type": "application/json",
      "Charset": "utf-8",
    },
    body: jsonEncode({'UserID': 1}),
  );

  if (response.statusCode == 200) {
    final Map<String, dynamic> responseMap = json.decode(response.body);
    // data字段为单个Map对象,不是List
    final Map<String, dynamic> customerData = responseMap["data"];
    
    customerList.clear();
    customerList.add(GetCustomer.fromJson(customerData));
    return customerList;
  } else {
    // 请求失败可根据业务需求返回空列表或抛出对应异常
    return customerList;
  }
}

优化建议

  • 原代码中new Map<String, dynamic>.from(json.decode(response.body))属于冗余写法,json.decode处理JSON对象时默认返回Map<String, dynamic>类型,无需额外做Map转换
  • 解析前可增加字段类型校验,比如判断responseMap["data"] is Map后再做解析,避免接口偶发返回异常结构导致App崩溃
  • 只有当接口返回的data字段是用[]包裹的数组结构时,才需要用List<dynamic>接收后循环遍历解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:01:07