【问题标题】:Flutter Json Encode ListFlutter Json 编码列表
【发布时间】:2025-12-11 16:25:01
【问题描述】:

如何将列表编码为 json?

这是我的 Json 课程。

class Players{
  List<Player> players;

  Players({this.players});

  factory Players.fromJson(List<dynamic> parsedJson){

    List<Player> players = List<Player>();
    players = parsedJson.map((i)=>Player.fromJson(i)).toList();

    return Players(
      players: players,
    );
  }
}

class Player{
  final String name;
  final String imagePath;
  final int totalGames;
  final int points;

  Player({this.name,this.imagePath, this.totalGames, this.points});

  factory Player.fromJson(Map<String, dynamic> json){

    return Player(
      name: json['name'],
      imagePath: json['imagePath'],
      totalGames: json['totalGames'],
      points: json['points'],
    );
  }
}

我设法用 fromJson 解码,结果在 List 中。现在我有另一个玩家要添加 json 并想将列表编码为 json,不知道怎么做。结果总是失败。

var json = jsonDecode(data);
List<Player> players = Players.fromJson(json).players;
Player newPlayer = Player(name: _textEditing.text,imagePath: _imagePath,totalGames: 0,points: 0);
players.add(newPlayer);
String encode = jsonEncode(players.players);

我需要在播放器或播放器上添加什么?

【问题讨论】:

  • 您的代码不正确。 players 变量的类型为 List。因此,此代码players.players 将不起作用,因为List 没有players 字段。

标签: json list flutter dart


【解决方案1】:

toJson 方法添加到您的Player 类中:

Map<String, dynamic> toJson(){
  return {
    "name": this.name,
    "imagePath": this.imagePath,
    "totalGames": this.totalGames,
    "points": this.points
  };
}

那你可以在玩家名单上拨打jsonEncode

String encoded = jsonEncode(players) // this will automatically call toJson on each player

【讨论】:

  • 你不需要静态函数。如果类实现了 toJsonjsonEncode 将与 List&lt;Player&gt; 一起使用。
  • @Lucas 你是对的!不需要静态功能。谢谢!
【解决方案2】:

添加类:

Map<String,dynamic> toJson(){
    return {
        "name": this.name,
        "imagePath": this.imagePath,
        "totalGames": this.totalGames,
        "points": this.points
    };
  }

然后打电话

String json = jsonEncode(players.map((i) => i.toJson()).toList()).toString();

【讨论】:

  • 你能解释一下为什么变量 json 被声明为 String 吗?我很困惑
  • 嗨,史蒂文,有时我们需要将 json 用作纯文本/文本,但这只是一个示例。
【解决方案3】:
List jsonList = players.map((player) => player.toJson()).toList();
print("jsonList: ${jsonList}");

【讨论】:

  • 您能否添加说明为什么这可以解决问题中提到的问题?