Flutter中JSON字段int/String转double解析异常求助
解决Flutter中JSON字段类型不固定(int/String转double)的问题
这确实是后端接口类型不规范导致的常见问题,不是Dart的bug!咱们可以通过类型判断+统一转换的方式来处理这种字段类型摇摆的情况,下面给你两种靠谱的解决思路:
方法一:明确类型分支处理
通过is关键字判断字段的实际类型,分别处理String、int甚至double的情况,逻辑清晰且覆盖全面:
factory ShippingMethod.fromJson(Map<String, dynamic> json) { dynamic costValue = json['cost']; double cost; if (costValue is String) { // 字符串类型先转成num,再转double cost = num.parse(costValue).toDouble(); } else if (costValue is int) { // int类型直接转double cost = costValue.toDouble(); } else if (costValue is double) { // 兼容后端偶尔返回double的情况 cost = costValue; } else { // 兜底处理,比如给默认值0.0,也可以根据业务抛出异常 cost = 0.0; } return ShippingMethod( code: json['code'], title: json['title'], description: json['description'], cost: cost, taxClassId: json['tax_class_id'], ); }
方法二:用num统一转换(更简洁)
利用num是int和double的父类特性,先把所有类型统一转成num,再转成double,代码更紧凑:
factory ShippingMethod.fromJson(Map<String, dynamic> json) { dynamic costValue = json['cost']; double cost; try { // 字符串转num,其他类型直接强转为num num temp = costValue is String ? num.parse(costValue) : costValue as num; cost = temp.toDouble(); } catch (e) { // 转换失败时的兜底处理,避免崩溃 cost = 0.0; print('解析cost字段出错: $e'); } return ShippingMethod( code: json['code'], title: json['title'], description: json['description'], cost: cost, taxClassId: json['tax_class_id'], ); }
为什么你之前的方法会报错?
json['cost'].toDouble():当字段是String类型时,String类没有toDouble()方法,自然触发NoSuchMethodError;int.parse(json['cost']):当字段是int类型时,int不能直接传给需要String参数的int.parse(),所以报类型不匹配;- 直接赋值:Dart是强类型语言,int和double是不同的类型,不能直接把int赋值给double类型变量,因此触发类型转换异常。
内容的提问来源于stack exchange,提问作者Atamyrat Babayev
相关产品推荐
相关产品推荐

