Flutter中嵌套JSON无法映射到自定义模型的类型不匹配问题
解决嵌套JSON到CategoryModel的映射问题
1. 修正Results类的fromJson方法错误
你已经定位到核心问题:Results类初始化children列表时误用了json['results'],必须改为json['children'],这是嵌套映射失败的关键原因。
修正后的Results类代码:
class Results { final String id; final String name; final List<Results>? children; Results({required this.id, required this.name, this.children}); factory Results.fromJson(Map<String, dynamic> json) { return Results( id: json['id'] as String, name: json['name'] as String, // 修正:从json['children']读取子列表数据 children: (json['children'] as List?) ?.map((childJson) => Results.fromJson(childJson)) .toList(), ); } }
2. 确保CategoryModel的类型匹配
错误提示“参数类型‘ListList<Results>。
正确的CategoryModel代码:
class CategoryModel { final List<Results> results; CategoryModel({required this.results}); factory CategoryModel.fromJson(Map<String, dynamic> json) { return CategoryModel( results: (json['results'] as List) .map((resultJson) => Results.fromJson(resultJson)) .toList(), ); } }
3. 验证调用逻辑
解析接口返回的JSON时,确保正确调用模型的fromJson方法:
// 假设response是接口返回的响应对象 final Map<String, dynamic> jsonData = jsonDecode(response.body); final CategoryModel categoryModel = CategoryModel.fromJson(jsonData);
关键检查点
- 确认JSON结构与模型字段完全对应:顶级字段为
results数组,每个元素的子数组字段是children - 处理空值场景:如果children可能为空,模型中对应属性需设为可空类型
List<Results>? - 所有列表类型转换必须严格匹配,避免出现隐式类型转换错误
内容的提问来源于stack exchange,提问作者Amin Azizzadeh
相关产品推荐
相关产品推荐

