首页 > 解决方案 > 如何从 Flutter 中获取 JSON 数据

问题描述

我一直在尝试从我的颤振应用程序中获取 json 数据。我设法在我的控制台上打印了整个 json。我只想从此 json 中获取“分数”值。我该怎么做?

  final String url = "http://www.mocky.io/v2/5aa3f9ee310000c21926e2f8";

  Future<String> getJsonData() async{
    http.Response response = await http.get(
      Uri.encodeFull(url),
      headers: {"Accept" : "application/json"}
    );
     print(response.body);

    List data = json.decode(response.body);
    print(data[0]["score"]);

  }

标签: androidasynchronousflutterhybrid-mobile-app

解决方案


将最后两行更新为

 Map<String, dynamic> data = json.decode(response.body);
 print(data["score"]);

说明:您从 API 收到的数据不是 JSON 数组,而是它的 JSON 对象,因此您应该解码对地图的响应,并从该地图中获取分数字段。


推荐阅读