Flutter JSON转对象报错NoSuchMethodError的排查与解决
问题排查与解决方案
核心问题分析
出现NoSuchMethodError: Class _Map<String, dynamic> has no instance getter 'id'的原因是:MyDto的reply列表中存储的是原始JSON Map对象,而非Comment实例,直接访问.id时自然找不到对应属性。同时代码中还存在其他几处映射错误:
Comment类的fromJson方法中,pId错误映射到了json["text"],导致属性赋值错误。MyDto的reply使用List<dynamic>类型,未对数组元素做Comment转换。MyDto的toJson方法错误使用jsonEncode(reply),破坏了JSON结构。fetchData中late变量未处理请求失败的初始化问题。
修正后的代码
1. 修正Comment类
class Comment { String? id; String? pId; String? text; Comment({this.id, this.pId, this.text}); factory Comment.fromJson(Map<String, dynamic> json) => Comment( id: json["id"] as String?, pId: json["pId"] as String?, // 修正映射key,从text改为pId text: json["text"] as String?, ); Map<String, dynamic> toJson() => { "id": id, "pId": pId, "text": text, }; }
2. 修正MyDto类
class MyDto { Comment? comment; List<Comment>? reply; // 明确类型为List<Comment>,替代dynamic MyDto({this.comment, this.reply}); factory MyDto.fromJson(Map<String, dynamic> json) => MyDto( comment: Comment.fromJson(json['comment']), // 将reply数组中的每个Map转换为Comment实例 reply: json["reply"] != null ? (json["reply"] as List<dynamic>) .map((item) => Comment.fromJson(item as Map<String, dynamic>)) .toList() : null, ); Map<String, dynamic> toJson() => { "comment": comment?.toJson(), // 调用Comment的toJson方法 "reply": reply?.map((comment) => comment.toJson()).toList(), // 逐个转换Comment为JSON }; }
3. 修正fetchData方法
static Future<List<MyDto>> fetchData() async { final response = await http.get(Uri.parse("你的接口地址")); // 补全请求逻辑 if (response.statusCode == HttpStatus.ok) { final body = jsonDecode(response.body) as List<dynamic>; return body.map((item) => MyDto.fromJson(item as Map<String, dynamic>)).toList(); } else { // 处理请求失败场景,避免未初始化错误 throw Exception('请求失败,状态码: ${response.statusCode}'); // 或返回空列表:return []; } }
修正关键点说明
- 类型明确化:将
MyDto的reply改为List<Comment>,确保列表元素类型统一。 - JSON转对象完整转换:在
MyDto.fromJson中遍历reply数组,将每个Map转换为Comment实例,解决属性访问错误。 - 修复映射错误:修正
Comment类中pId的JSON key映射。 - 正确生成JSON:
toJson方法依赖Comment自身的toJson生成结构,避免手动编码导致的格式问题。 - 错误处理:移除
late变量,明确处理请求失败的情况,避免运行时初始化异常。
内容的提问来源于stack exchange,提问作者Eliasu
相关产品推荐
相关产品推荐

