Flutter嵌套JSON数据显示错误求助:类型不匹配与方法未定义
问题解决:Flutter嵌套JSON解析与展示错误
错误原因分析
1. 类型不匹配错误(期望'int?'却得到'String')
JSON数据中以下字段为字符串类型,但Model类被错误定义为int类型:
village_id:值为字符串格式编号(如"3174031001")crime_time.id:UUID格式字符串(如"5562f55f-54aa-4e94-9f6c-9ce25d9e3fd9")village.id:字符串格式编号(如"3174031001")
2. "方法fromjson未定义于data类型"错误
主要是解析JSON列表时调用了错误的方法名,或是Model类的fromJson方法参数类型不规范,导致无法正确识别解析逻辑。
修正后的Model类代码
class RangkumanKasus { int? department_id; String? crime_time_id; String? village_id; // 修正为String类型 int? cases; int? villages; int? target_id; String? department; final CrimeTime crime_time; final Village village; RangkumanKasus({ this.department_id, this.crime_time_id, this.village_id, this.cases, this.villages, this.target_id, this.department, required this.crime_time, required this.village, }); factory RangkumanKasus.fromJson(Map<String, dynamic> json) { return RangkumanKasus( department_id: json["department_id"], crime_time_id: json['crime_time_id'], village_id: json['village_id'], cases: json['cases'], villages: json['villages'], target_id: json['target_id'], department: json['department'], crime_time: CrimeTime.fromJson(json['crime_time']), village: Village.fromJson(json['village']), ); } } class CrimeTime { String? id; // 修正为String类型 String? name; CrimeTime({ this.id, this.name, }); factory CrimeTime.fromJson(Map<String, dynamic> json) { // 参数类型统一为Map<String, dynamic> return CrimeTime( id: json['id'], name: json['name'], ); } } class Village { String? id; // 修正为String类型 String? name; Village({ this.id, this.name, }); factory Village.fromJson(Map<String, dynamic> json) { // 参数类型统一为Map<String, dynamic> return Village( id: json['id'], name: json['name'], ); } }
修正JSON解析逻辑(解决第二个错误)
确保在获取数据的Future方法中,正确使用修正后的Model类解析JSON数组:
Future<List<RangkumanKasus>> fetchData() async { final response = await http.get(Uri.parse("你的API接口地址")); if (response.statusCode == 200) { final List<dynamic> dataList = json.decode(response.body)['result']; return dataList.map((jsonItem) => RangkumanKasus.fromJson(jsonItem)).toList(); } else { throw Exception("数据请求失败"); } }
优化数据展示代码(空安全处理)
避免使用!强制解包可能为空的字段,改用空安全运算符防止崩溃:
Container( child: FutureBuilder<List<RangkumanKasus>>( future: fetchData(), // 替换为你的数据请求Future builder: (context, snapshot) { if (snapshot.hasData) { List<RangkumanKasus> isiData = snapshot.data!; return ListView.builder( shrinkWrap: true, itemCount: isiData.length, itemBuilder: (context, index) { return Container( child: Text( isiData[index].crime_time.name ?? "未知时段", // 空安全兜底处理 style: TextStyle(color: Colors.red), ), ); }, ); } else if (snapshot.hasError) { return Text("错误:${snapshot.error}"); } return const CircularProgressIndicator(); }, ), )
内容的提问来源于stack exchange,提问作者Denise Aldianto
相关产品推荐
相关产品推荐

