Flutter Json编码列表

wil*_*aya 5 json list dart flutter

如何将列表编码为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'],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我设法用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);
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*son 11

添加类:

Map<String,dynamic> toJson(){
    return {
        "name": this.name,
        "imagePath": this.imagePath,
        "totalGames": this.totalGames,
        "points": this.points
    };
  }
Run Code Online (Sandbox Code Playgroud)

并打电话

String json = jsonEncode(players.map((i) => i.toJson()).toList()).toString();
Run Code Online (Sandbox Code Playgroud)


Sam*_*ani 9

首先将以下两个功能添加到播放器类中:

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;
}
Run Code Online (Sandbox Code Playgroud)

那么您需要对players列表进行以下操作

List jsonList = Player.encondeToJson(players);
print("jsonList: ${jsonList}");
Run Code Online (Sandbox Code Playgroud)

  • 您不需要静态功能。如果该类实现了toJson,则jsonEncode可以与List &lt;Player&gt;一起使用。 (3认同)

Fre*_*Cha 5

List jsonList = players.map((player) => player.toJson()).toList();
print("jsonList: ${jsonList}");
Run Code Online (Sandbox Code Playgroud)

  • 您能否添加说明,说明为什么这可以解决问题中提到的问题? (3认同)