Flutter Json Encode List

前端 未结 3 818
闹比i
闹比i 2020-12-11 03:02

How to encode list to json?

This is my class for Json.

class Players{
  List players;

  Players({this.players});

  factory Players.fr         


        
相关标签:
3条回答
  • 2020-12-11 03:12

    Add toJson method to your Player class:

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

    Then you can call jsonEncode on the list of players:

    String encoded = jsonEncode(players) // this will automatically call toJson on each player
    
    0 讨论(0)
  • 2020-12-11 03:14
    List jsonList = players.map((player) => player.toJson()).toList();
    print("jsonList: ${jsonList}");
    
    0 讨论(0)
  • 2020-12-11 03:27

    Add on class:

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

    and call

    String json = jsonEncode(players.map((i) => i.toJson()).toList()).toString();
    
    0 讨论(0)
提交回复
热议问题