如何在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
相关产品推荐
相关产品推荐

