如何从json列表中返回对象?

时间:2019-08-20 02:46:52

标签: flutter dart flutter-layout

我有一个func,它发出一个get http请求,然后返回以下内容:

return json.decode(response.body);

问题在于响应是一个列表,如下所示:

[
   {"name":"le me","score":"5,400,000,000","rank":"1"},
   {"name":"Scuzzy","score":"5,400,000,000","rank":"2"}
]

但是我无法返回此列表,我需要返回一张地图,该列表[]中的对象。

const requestRank = "https://secure.runescape.com/m=hiscore/a=869/ranking.json?table=0&category=0&size=5";

Future<Map> _runeRequest() async {
    http.Response response= await http.get(requestRank);
   print((response.body));
    return json.decode(response.body);
  }


Widget buildRankTable() {
    return FutureBuilder<Map>(
      future: _runeRequest(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return _buildRank("1", "1", "1", "1", false);
          default:
            if (snapshot.hasError) {
              print(snapshot.error.toString());
              return _buildRank("2", "2", "2", "2", false);
            } else {
              String rank, player, xp;
                for (int i = 0; i < snapshot.data.length; i++) {
                rank = snapshot.data["rank"];
                player = snapshot.data["name"];
                xp = snapshot.data["score"];
                print("º Rank=> " + rank);
                print("º player=> " + player);
                if (i % 2 == 0)
                  return _buildRank(rank, player, "2736", xp, false);
                else
                  return _buildRank(rank, player, "2736", xp, false);
              }
              return _buildRank(rank, player, "2736", xp, false);
            }
        }
      },
    );
  }

我收到此错误:

  

“列表”类型不是“ FutureOr>”类型的子类型

我认为问题是我要在函数FutureBuilder中将列表返回到buildRankTable。所以我需要输入return map,并且在func _runeRequest的响应中没有列表,对吧?

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码将json转换为map: 地图学生= jsonDecode(jsonString);

更多详细信息是here

理想地,您必须为单个数组创建一个类并定义一个.fromJson方法。这样可以更好地处理错误,并分离出数据和UI部分。

以下示例:

class Student {
final string name ;
.....

Student({
@required this.name,
// ... 

Student.fromJson(Map json)
  : this.name = json["name"],
    this.score = json["score"],
    this.rank = json["rank"]
}

然后,您必须将从服务器收到的JSON传递给此类以进行实例化。您可以同时制作列表。下面的示例:

Future<List>Students getStudentList() {

   // ... API Call

    return (decodedBody["StudentList"] as List)
            .map((element) => Student.fromJson(element))
            .toList();
}

答案 1 :(得分:0)

创建模型

class LeaderboardModel{
    String name;
    String score;
    String rank;
    LeaderboardModel({this.name,this.score,this.rank});
    factory LeaderboardModel.fromJson(Map<String,dynamic> json){
    return LeaderboardModel(
      name : json["name"],
      score : json["score"],
      rank : json["rank"],
    );
  }
}

创建功能

Future<List<LeaderboardModel>> readLeaderboard() async{
    final response = await http.get("https://secure.runescape.com/m=hiscore/a=869/ranking.json?table=0&category=0&size=5");
    if (response.statusCode == 200) {
        return parseLeaderboard(response.body);
    } else {
        throw Exception('Failed to load post');
    }
}

List<LeaderboardModel> parseLeaderboard(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<LeaderboardModel>((json) => LeaderboardModel.fromJson(json)).toList();
}

希望这会有所帮助