Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Json Encode List

How to encode list to json?

This is my class for 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'],
    );
  }
}

I managed to decode with fromJson, the result is in List. Now that I have another player to add in json and want to encode the list to json, have no idea to do it. It result always failed.

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);

What do I need to add on Players or Player?

like image 842
willy wijaya Avatar asked Mar 06 '19 13:03

willy wijaya


People also ask

How do I encode list into JSON in flutter?

We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.

What is the use of JSON encode in flutter?

jsonEncode function Null safetyConverts object to a JSON string. If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.


2 Answers

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
like image 74
Sami Kanafani Avatar answered Sep 17 '22 19:09

Sami Kanafani


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();
like image 30
Lucio Pelinson Avatar answered Sep 21 '22 19:09

Lucio Pelinson