如何将列表编码为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);
我需要在Player或Player上添加什么?
答案 0 :(得分:7)
添加课程:
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();
答案 1 :(得分:2)
首先将以下两个功能添加到播放器类中:
Map<String,dynamic> toJson(){
return {
"name": this.name,
"imagePath": this.imagePath,
"totalGames": this.totalGames,
"points": this.points
};
}
static List encondeToJson(List<Player>list){
List jsonList = List();
list.map((item)=>
jsonList.add(item.toJson())
).toList();
return jsonList;
}
然后您需要对players
列表进行以下操作
List jsonList = Player.encondeToJson(players);
print("jsonList: ${jsonList}");
答案 2 :(得分:0)
List jsonList = players.map((player) => player.toJson()).toList();
print("jsonList: ${jsonList}");