Flutter JSON编码列表



如何将列表编码为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进行了解码,结果在列表中。现在,我有另一个播放器要添加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);

我需要添加什么玩家或玩家?

添加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

添加类:

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();
List jsonList = players.map((player) => player.toJson()).toList();
print("jsonList: ${jsonList}");

最新更新