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

如何在Flutter中将JSON中的ProdList转换为List<Prod>

解决方案

1. 完善Prod类,添加JSON转对象的方法

你的Prod类需要新增工厂方法,用来将单个JSON对象转换为Prod实例,同时处理JSON字段(大写开头)和类属性(小写开头)的映射,以及字符串到数字的类型转换:

class Prod {
  int? pCode;
  String? pName;
  String? pIdCode;
  int? pGCode;
  String? pGName;
  int? pGCategory;
  String? pPack;
  double? pRate;
  String? pDisc;
  String? pImage;

  Prod({
    this.pCode,
    this.pName,
    this.pIdCode,
    this.pGCode,
    this.pGName,
    this.pGCategory,
    this.pPack,
    this.pRate,
    this.pDisc,
    this.pImage,
  });

  // 工厂方法:从JSON生成Prod实例
  factory Prod.fromJson(Map<String, dynamic> json) {
    return Prod(
      pCode: int.tryParse(json['PCode'] ?? ''),
      pName: json['PName'],
      pIdCode: json['PIdCode'],
      pGCode: int.tryParse(json['PGCode'] ?? ''),
      pGName: json['PGName'],
      pGCategory: int.tryParse(json['PGCategory'] ?? ''),
      pPack: json['PPack'],
      pRate: double.tryParse(json['PRate'] ?? ''),
      pDisc: json['PDisc'],
      pImage: json['PImage'],
    );
  }
}

2. 修改fetchProd方法,正确解析ProdList

注意:JSON中的ProdList是数组(List),不是Map,你之前的代码错误地将其当作Map处理。正确的做法是遍历数组元素,逐个转换为Prod对象:

Future fetchProd() async {
  var client = http.Client();
  try {
    Uri web = Uri.https("website address");
    var response = await client.get(web);

    if (response.statusCode == 200) {
      Map<String, dynamic> result = jsonDecode(response.body) as Map<String, dynamic>;
      if (result["status"] as int == 1) {
        // 转换ProdList为List<Prod>
        List<dynamic> prodJsonList = result["ProdList"] as List<dynamic>;
        GlobalVariable.prodList = prodJsonList
            .map((prodJson) => Prod.fromJson(prodJson as Map<String, dynamic>))
            .toList();
      }
    } else {
      throw Exception('请求失败,状态码:${response.statusCode}');
    }
  } catch (e) {
    rethrow;
  } finally {
    client.close();
  }
}

关键注意事项

  • 使用int.tryParse和double.tryParse是为了安全转换字符串类型的数字,避免因JSON字段为空或格式错误导致崩溃。
  • 确保GlobalVariable.prodList的类型声明为List<Prod>,否则需要调整变量类型匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:50:13