android - Flutter JSON 无法正确读取
问题描述
这可能需要一段时间......我一直在尝试让我的 Dart/Flutter 代码从BlockChainTicker返回数据(特别是我想查看 AUD 行中的所有内容)并将其留在调试控制台中。当我这样做时,我从控制台收到此错误
E/flutter ( 8656): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 8656): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' where
E/flutter ( 8656): _InternalLinkedHashMap is from dart:collection
E/flutter ( 8656): String is from dart:core
E/flutter ( 8656): List is from dart:core
我的代码可能看起来很成熟,但我在这门语言方面只有大约一周的经验,所以感谢您耐心阅读本文。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class First extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<First> {
List data;
Future<String> getData() async {
var response = await http.get(
Uri.encodeFull("http://blockchain.info/ticker"),
headers: {
"Accept": "application/json"
}
);
data = JSON.decode(response.body);
print(data[1]["AUD"]);
return "Success!";
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new RaisedButton(
child: new Text("Get data"),
onPressed: getData,
),
),
);
}
}
解决方案
json 的顶层是地图(不是列表 - 在 json 中,列表括在括号中)
{
"USD" : {"15m" : 7492.85, "last" : 7492.85, "buy" : 7492.85, "sell" : 7492.85, "symbol" : "$"},
"AUD" : {"15m" : 9899.28, "last" : 9899.28, "buy" : 9899.28, "sell" : 9899.28, "symbol" : "$"},
"BRL" : {"15m" : 28214.31, "last" : 28214.31, "buy" : 28214.31, "sell" : 28214.31, "symbol" : "R$"},
所以改变:
print(data[1]["AUD"]);
至
print(data["AUD"]); // prints the whole AUD map
print(data['AUD']['last']); // prints the AUD 'last' double
String isoCode = 'AUD';
print('$isoCode -> ${data[isoCode]}');
推荐阅读
- javascript - 使用我从 API 带来的数据呈现卡片时出现问题
- r - GLMMadaptive (R) 中的零膨胀两部分模型:固定效应零部分的方差分析?
- javascript - 如何解决 Next.Js 中的内部服务器错误?
- python-3.x - 尽管代码在 try 块中,我如何处理错误
- python - 合并到新表时如何覆盖旧的现有 ID?
- laravel - 如何在laravel中的子查询中求和
- ruby-on-rails - WickedPDF 在尝试呈现多个 pdf 时生成空白 pdf
- express - 无法使用 axios 从 API 获取当前用户
- woocommerce - 显示过滤产品时如何覆盖/shop/页面上的类别模板?
- python - 使用机器人发送不和谐消息时记录其 id