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

如何修复Dart代码转换时出现的错误?

Dart数据转换错误解决方法

问题分析

从错误信息可知,你直接将jsonDecode返回的List<dynamic>强制转换为List<Product>,Dart不允许这种直接类型强转——运行时无法确保列表内每个元素都是Product类型,因此抛出类型转换异常。

正确实现方案

1. 定义带JSON解析能力的Product模型

先为Product类添加从JSON对象生成实例的构造函数:

class Product {
  final String id;
  final String name;
  final double price;

  Product({required this.id, required this.name, required this.price});

  // 从JSON映射转换为Product实例
  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'] as String,
      name: json['name'] as String,
      price: (json['price'] as num).toDouble(),
    );
  }
}

2. 正确解析JSON数组

遍历解码后的动态列表,逐个将元素转换为Product对象,而非直接强转:

import 'dart:convert';

void main() {
  // 示例JSON字符串
  const jsonString = '''
    [
      {"id": "p1", "name": "笔记本", "price": 3999},
      {"id": "p2", "name": "鼠标", "price": 99}
    ]
  ''';

  // 解码为动态列表
  final List<dynamic> rawList = jsonDecode(jsonString);
  // 遍历转换为Product列表
  final List<Product> products = rawList
      .map((item) => Product.fromJson(item as Map<String, dynamic>))
      .toList();

  print(products);
}

3. 可选:添加异常处理

如果JSON数据格式可能存在异常,建议捕获解析错误:

List<Product> parseProducts(String jsonString) {
  try {
    final List<dynamic> rawList = jsonDecode(jsonString);
    return rawList
        .map((item) => Product.fromJson(item as Map<String, dynamic>))
        .toList();
  } catch (e) {
    print('JSON解析失败: $e');
    return [];
  }
}

内容的提问来源于stack exchange,提问作者ali miri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:30:49