gpt4 book ai didi

json - Flutter Json 编码列表

转载 作者:IT王子 更新时间:2023-10-29 06:36:23 24 4
gpt4 key购买 nike

如何将列表编码成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 或 Player 上添加什么?

最佳答案

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

关于json - Flutter Json 编码列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55024549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com