You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将双层嵌套JSON列表转换为Dart模型

解决Dart解析双层嵌套列表standings的问题

你的核心问题在于解析standings字段时,直接将JSON中的Map对象添加到List<Standing>中,没有转换为Standing模型实例。另外需要注意JSON结构:standings是一个双层列表(外层列表包含一个内层列表,内层列表才是所有球队的排名数据)。

修正后的StandingLeague.fromJson方法

class StandingLeague {
  int? id;
  String? name;
  String? country;
  String? logo;
  String? flag;
  int? season;
  List<Standing>? standings;

  StandingLeague.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    country = json['country'];
    logo = json['logo'];
    flag = json['flag'];
    season = json['season'];
    if (json['standings'] != null && json['standings'].isNotEmpty) {
      standings = <Standing>[];
      // 取出外层列表的第一个元素(内层球队列表),遍历并转换为Standing实例
      json['standings'][0].forEach((v) {
        standings?.add(Standing.fromJson(v));
      });
    }
  }
}

完整的配套模型类

需要定义所有嵌套结构的模型类,确保每个层级都能正确解析:

// 球队排名模型
class Standing {
  int? rank;
  Team? team;
  int? points;
  int? goalsDiff;
  String? group;
  String? form;
  String? status;
  String? description;
  MatchStats? all;
  MatchStats? home;
  MatchStats? away;
  String? update;

  Standing.fromJson(Map<String, dynamic> json) {
    rank = json['rank'];
    team = json['team'] != null ? Team.fromJson(json['team']) : null;
    points = json['points'];
    goalsDiff = json['goalsDiff'];
    group = json['group'];
    form = json['form'];
    status = json['status'];
    description = json['description'];
    all = json['all'] != null ? MatchStats.fromJson(json['all']) : null;
    home = json['home'] != null ? MatchStats.fromJson(json['home']) : null;
    away = json['away'] != null ? MatchStats.fromJson(json['away']) : null;
    update = json['update'];
  }
}

// 球队信息模型
class Team {
  int? id;
  String? name;
  String? logo;

  Team.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    logo = json['logo'];
  }
}

// 比赛统计模型
class MatchStats {
  int? played;
  int? win;
  int? draw;
  int? lose;
  Goals? goals;

  MatchStats.fromJson(Map<String, dynamic> json) {
    played = json['played'];
    win = json['win'];
    draw = json['draw'];
    lose = json['lose'];
    goals = json['goals'] != null ? Goals.fromJson(json['goals']) : null;
  }
}

// 进球数据模型
class Goals {
  int? forGoals;
  int? against;

  Goals.fromJson(Map<String, dynamic> json) {
    forGoals = json['for'];
    against = json['against'];
  }
}

解析完整JSON响应

注意外层JSON包含league字段,所以解析时需要先获取该字段:

// 假设response是你的JSON响应Map
var leagueData = StandingLeague.fromJson(response['league']);
// 此时leagueData.standings就是解析后的球队排名列表

内容的提问来源于stack exchange,提问作者alfietap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:20:13