Flutter Json编码列表 [英] Flutter Json Encode List

查看:99
本文介绍了Flutter Json编码列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将列表编码为json?

How to encode list to 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,现在不知道要这样做了.结果总是失败.

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

我需要在Player或Player上添加什么?

What do I need to add on Players or Player?

推荐答案

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

first add to your player class the 2 functions below:

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

然后您需要对players列表进行以下操作

then you need to do the following with your players list

List jsonList = Player.encondeToJson(players);
print("jsonList: ${jsonList}");

这篇关于Flutter Json编码列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆