Flutter使用json_serializable导入本地JSON文件并完成转换问题咨询
问题原因说明
两个报错的核心诱因如下:
- 错误使用
import导入JSON文件:Dart的import仅用于导入 Dart 代码文件,你声明的as countryList被识别为导入前缀,不能直接作为变量传入方法,因此触发第二个报错。 - 实体类与JSON结构不匹配:你的JSON根节点是数组,但是
CountryList.fromJson默认接收Map<String, dynamic>类型参数,同时CountryListDetail构造函数参数名与字段名不匹配,触发第一个类型错误。
步骤1:配置静态资源路径
首先将country_list.json放入项目静态资源目录,比如新建assets/json文件夹并移入文件,随后打开项目根目录的pubspec.yaml,在flutter配置块下添加资源声明:
flutter: # 原有配置保持不变,新增以下资源声明 assets: - assets/json/country_list.json
添加完成后执行flutter pub get使配置生效。
步骤2:修正实体类代码
修正构造参数不匹配问题,同时补充适配根数组的解析方法:
import 'package:json_annotation/json_annotation.dart'; part 'country_list.g.dart'; // 替换为你实际的文件名+.g.dart @JsonSerializable() class CountryList { final List<CountryListDetail> countryList; CountryList(this.countryList); // 新增适配根数组的工厂方法 factory CountryList.fromJsonList(List<dynamic> jsonList) { final list = jsonList.map((item) => CountryListDetail.fromJson(item)).toList(); return CountryList(list); } factory CountryList.fromJson(Map<String, dynamic> json) => _$CountryListFromJson(json); Map<String, dynamic> toJson() => _$CountryListToJson(this); } @JsonSerializable() class CountryListDetail { final String? country; final String? name; final double? lat; final double? long; // 修正构造参数与字段名一致 CountryListDetail(this.country, this.name, this.lat, this.long); factory CountryListDetail.fromJson(Map<String, dynamic> json) => _$CountryListDetailFromJson(json); Map<String, dynamic> toJson() => _$CountryListDetailToJson(this); }
修改完成后重新执行序列化代码生成命令:flutter pub run build_runner build
步骤3:加载并解析JSON文件
通过Flutter官方的资源加载工具读取文件内容后再解析,示例代码如下:
import 'package:flutter/services.dart'; import 'dart:convert'; // 异步加载解析方法 Future<CountryList> loadCountryData() async { // 读取JSON文件文本内容 final jsonStr = await rootBundle.loadString('assets/json/country_list.json'); // 解码为Dart可操作的数组结构 final jsonArray = jsonDecode(jsonStr); // 转换为实体类返回 return CountryList.fromJsonList(jsonArray); } // 赋值给变量a(需要在异步方法中执行) var a = await loadCountryData();
内容的提问来源于stack exchange,提问作者chichi
相关产品推荐
相关产品推荐

