Flutter解析DuckDuckGo API的RelatedTopics JSON数据失败求助
问题排查与解析方案
问题点分析
- 数据模型MyModel和Icon缺少
fromJson构造函数,无法将JSON数据映射为Dart对象。 RelatedTopics是JSON数组而非单个对象,直接用MyModel.fromJson(res)解析整个数组会导致类型不匹配错误。- 解析方法中直接返回单个对象包装的列表,不符合API返回的多个数据项的实际情况。
正确实现方案
1. 完善数据模型(添加fromJson构造函数)
class MyModel { final String? firstUrl; final Icon? icon; final String? result; final String? text; MyModel({ this.firstUrl, this.icon, this.result, this.text, }); // 从JSON映射到MyModel factory MyModel.fromJson(Map<String, dynamic> json) { return MyModel( firstUrl: json['FirstURL'], icon: json['Icon'] != null ? Icon.fromJson(json['Icon']) : null, result: json['Result'], text: json['Text'], ); } } class Icon { final String? height; final String? url; final String? width; Icon({ this.height, this.url, this.width, }); // 从JSON映射到Icon factory Icon.fromJson(Map<String, dynamic> json) { return Icon( height: json['Height'], url: json['URL'], width: json['Width'], ); } }
2. 修正fetchData解析方法
Future<List<MyModel>> fetchData() async { final response = await client.get(AppEndpoints.myurl); final data = jsonDecode(response.data); // 获取RelatedTopics数组 final List<dynamic> topics = data['RelatedTopics']; // 遍历数组,逐个转换为MyModel对象 return topics.map((topic) => MyModel.fromJson(topic)).toList(); }
关键说明
- 注意JSON字段名的大小写:API返回的字段是
FirstURL、Icon、Result、Text,映射时要和JSON中的字段名完全匹配。 - 处理
Icon字段可能为null的情况,避免空指针异常。 - 使用
map方法遍历数组,将每个JSON对象转换为MyModel实例,最后转为List返回。
内容的提问来源于stack exchange,提问作者kalibear
相关产品推荐
相关产品推荐

