使用json_serializable解析本地JSON出现类型不匹配错误求助
Flutter json_serializable解析本地JSON报错:type 'List' is not a subtype of type 'Map<String, dynamic>'
错误信息
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>' #0 _MyHomePageState.loadRecipe (package:json_serializable_example/main.dart:64:46)
问题根源
你的recipe.json根结构是数组(List),但调用RecipeList.fromJson(jsonParsedResponse)时,该方法期望接收Map<String, dynamic>类型(对应外层带recipe字段的JSON对象),两者结构不匹配导致类型转换错误。
另外,Batters类中用Topping解析batter数组是可行的,因为batter数组内的元素结构和Topping类字段完全匹配(包含id和type),这部分无需修改。
解决方案
有两种可选修复方案:
方案1:直接解析JSON数组为List
修改loadRecipe方法,跳过RecipeList类,直接将JSON数组转换为List<Recipe>:
Future<List<Recipe>> loadRecipe() async { String response = await _loadARecipeAsset(); final jsonList = json.decode(response) as List<dynamic>; return jsonList.map((item) => Recipe.fromJson(item as Map<String, dynamic>)).toList(); }
方案2:调整RecipeList类适配数组解析
如果需要保留RecipeList类,修改其fromJson工厂方法,使其支持接收List类型输入:
// recipelist_response.dart @JsonSerializable(explicitToJson: true) class RecipeList{ List<Recipe> recipe; RecipeList({ required this.recipe, }); // 修改fromJson方法,接收List参数 factory RecipeList.fromJson(List<dynamic> json) => RecipeList( recipe: json.map((e) => Recipe.fromJson(e as Map<String, dynamic>)).toList(), ); Map<String, dynamic> toJson() => _$RecipeListToJson(this); }
同时更新loadRecipe方法:
Future<RecipeList> loadRecipe() async { String response = await _loadARecipeAsset(); final jsonList = json.decode(response) as List<dynamic>; RecipeList recipes = RecipeList.fromJson(jsonList); return recipes; }
注意:这种方式需要手动修改fromJson方法,自动生成的代码会被覆盖,后续重新生成代码时需再次调整。
额外建议
如果后续JSON结构可调整为外层带recipe字段的对象,可保留原有RecipeList类,只需修改JSON文件:
{ "recipe": [ // 原有数组内容 ] }
内容的提问来源于stack exchange,提问作者Shanmukha
相关产品推荐
相关产品推荐

