Flutter Dart Model构建求助:JSON响应中动态Map结构的映射问题
修正Flutter Dart数据模型中的动态Map序列化问题
我看到你的问题了——你把JSON里的report字段错误地定义成了List<Report>,但实际上它是一个以字符串ID为键、Report对象为值的Map结构,这直接导致了序列化/反序列化失败。下面是修正后的完整代码,我会逐一说明修改点:
核心修改说明
- 字段类型修正:在
GlobalNews类中,将report的类型从List<Report>改为Map<String, Report>,完全匹配JSON的实际结构。 - 调整fromJson方法:原来的
map操作已经返回Map<String, Report>,现在可以直接赋值给report字段,无需额外转换。 - 调整toJson方法:现在
report是Map类型,直接通过map方法将每个Report对象转为JSON格式即可,无需再用Map.from()包裹。
修正后的完整Dart Model代码
import 'dart:convert'; GlobalNews globalNewsFromJson(String str) => GlobalNews.fromJson(json.decode(str)); String globalNewsToJson(GlobalNews data) => json.encode(data.toJson()); class GlobalNews { GlobalNews({ required this.status, required this.report, required this.brt, required this.gameDate, }); String status; // 修正:将List<Report>改为Map<String, Report> Map<String, Report> report; DateTime brt; GameDate gameDate; factory GlobalNews.fromJson(Map<String, dynamic> json) => GlobalNews( status: json["status"], // 修正:直接赋值map后的结果(已经是Map<String, Report>类型) report: Map.from(json["report"]) .map((k, v) => MapEntry<String, Report>(k, Report.fromJson(v))), brt: DateTime.parse(json["brt"]), gameDate: GameDate.fromJson(json["gameDate"]), ); Map<String, dynamic> toJson() => { "status": status, // 修正:直接对Map类型的report做转换 "report": report.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())), "brt": brt.toIso8601String(), "gameDate": gameDate.toJson(), }; } class GameDate { GameDate({ required this.season, required this.round, required this.day, }); int season; int round; int day; factory GameDate.fromJson(Map<String, dynamic> json) => GameDate( season: json["season"], round: json["round"], day: json["day"], ); Map<String, dynamic> toJson() => { "season": season, "round": round, "day": day, }; } class Report { Report({ required this.id, required this.countryIso, required this.authorid, required this.publishDate, required this.title, }); String id; String countryIso; String authorid; DateTime publishDate; String title; factory Report.fromJson(Map<String, dynamic> json) => Report( id: json["id"], countryIso: json["country_iso"], authorid: json["authorid"], publishDate: DateTime.parse(json["publish_date"]), title: json["title"], ); Map<String, dynamic> toJson() => { "id": id, "country_iso": countryIso, "authorid": authorid, "publish_date": publishDate.toIso8601String(), "title": title, }; }
额外提示
如果之后你需要在UI中展示所有Report对象的列表,可以通过report.values.toList()快速将Map转换为List,比如:
// 获取所有Report的列表 List<Report> reportList = globalNews.report.values.toList();
内容的提问来源于stack exchange,提问作者Coenraad Vlietstra
相关产品推荐
相关产品推荐

