【发布时间】: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字段。