小编典典

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解码,结果在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);

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


阅读 339

收藏
2020-07-27

共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
2020-07-27