javascript - Flutter:从 IEX JSON API 检索股票统计信息和报价列表
问题描述
IEX JSON API:
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../models/stocks.dart';
Future<Map<String,dynamic>> getStocks() async {
// final String url =
'https://cloud.iexapis.com/stable/stock/market/batch?
symbols=aapl,fb&types=quote&token=Hidden';
// final client = new http.Client();
// final streamedRest = await client.send(
// http.Request('get', Uri.parse(url))
const url = 'https://cloud.iexapis.com/stable/stock/market/batch?s
ymbols=aapl,fb&types=quote&token=Hidden';
final response = await http.get(url);
final decodedResponse = json.decode(response.body).keys();
final data = Stocks.fromJson(decodedResponse);
//http.Response response = await http.get(Uri, headers: {"Accept":
"application/json"});
//print(jsonDecode(response.body).keys());
return jsonDecode(response.body).keys();
// return streamedRest.stream
// .transform(utf8.decoder)
// .transform(json.decoder)
// .expand((data) => (data as List<dynamic>))
// .map((data) => Stocks.fromJSON(data));
}
{"AAPL":{"stats":{"week52change":0.108189,"week52high":244.8,"week52low":142,"marketcap":1100781864400,"employees":132000,"day200MovingAvg":196.46,"day50MovingAvg" :220.62,"float":4512324403.94,"avg10Volume":23328121.8,"avg30Volume":26924247.43,"ttmEPS":11.8267,"ttmDividendRate":2.96,"companyName":"Apple, Inc.","sharesOutstanding":4519180000, "maxChangePercent":240.1683,"year5ChangePercent":1.315,"year2ChangePercent":0.5505,"year1ChangePercent":0.108189,"ytdChangePercent":0.542427,"month6ChangePercent":0.186574,"month3ChangePercent":0.176601,"month1ChangePercent":0.102022,"day0ChangePercent" “:0。113509,"day5ChangePercent":0.030329,"nextDividendDate":null,"dividendYield":0.012152065029969619,"nextEarningsDate":"2019-10-30","exDividendDate":"2019-08-09","perRatio":20.75, "beta":1.534551916699308},"quote":{"symbol":"AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"tops","open" :null,"openTime":null,"close":null,"closeTime":null,"high":null,"low":null,"latestPrice":245.395,"latestSource":"IEX 实时价格", “最新时间”:“12:37:57:0.012152065029969619,"nextEarningsDate":"2019-10-30","exDividendDate":"2019-08-09","perRatio":20.75,"beta":1.534551916699308},"quote":{"symbol":" AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"tops","open":null,"openTime":null,"close":null,"closeTime ":null,"high":null,"low":null,"latestPrice":245.395,"latestSource":"IEX 实时价格","latestTime":"12:37:57:0.012152065029969619,"nextEarningsDate":"2019-10-30","exDividendDate":"2019-08-09","perRatio":20.75,"beta":1.534551916699308},"quote":{"symbol":" AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"tops","open":null,"openTime":null,"close":null,"closeTime ":null,"high":null,"low":null,"latestPrice":245.395,"latestSource":"IEX 实时价格","latestTime":"12:37:57{"symbol":"AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"tops","open":null,"openTime":null,"close ":null,"closeTime":null,"high":null,"low":null,"latestPrice":245.395,"latestSource":"IEX 实时价格","latestTime":"12:37:57{"symbol":"AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"tops","open":null,"openTime":null,"close ":null,"closeTime":null,"high":null,"low":null,"latestPrice":245.395,"latestSource":"IEX 实时价格","latestTime":"12:37:57最新时间":"12:37:57最新时间":"12:37:57
日志:
在调试模式下在为 x86 构建的 Android SDK 上启动 lib\main.dart... 初始化 gradle... 解决依赖关系... 运行 Gradle 任务 'assembleDebug'... 构建 build\app\outputs\apk\debug\app-调试.apk。I/OpenGLRenderer(4854):初始化 EGL,版本 1.4 D/OpenGLRenderer(4854):交换行为 1 D/(4854):HostConnection::get() 新主机连接已建立 0xdc20bf00,tid 4881 D/EGL_emulation(4854):eglCreateContext : 0xe3d47760: maj 2 min 0 rcv 2 D/EGL_emulation(4854): eglMakeCurrent: 0xe3d47760: ver 2 0 (tinfo 0xc6b24a30) D/(4854): HostConnection::get() 新主机连接建立 0xc6b386c0, tid 4874 D/EGL_emulation (4854):eglCreateContext:0xdc27d780:maj 2 min 0 rcv 2 D/EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)正在将文件同步到为 x86 构建的设备 Android SDK... I/Choreographer(4854):跳过了 279 帧!应用程序可能在其主线程上做了太多工作。D/EGL_emulation(4854):eglMakeCurrent:0xe3d47760:ver 2 0(tinfo 0xc6b24a30)I/OpenGLRenderer(4854):戴维!持续时间=6180ms;Flags=1, IntendedVsync=596431275408, Vsync=601081275222, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=601083214976, AnimationStart=601083253387, PerformTraversalsStart=601083255696, DrawStart=601096302305, SyncQueued=601333900000, SyncStart=601335418694, IssueDrawCommandsStart=601335535183, SwapBuffers= 602308827762,FrameCompleted=602612881859,DequeueBufferDuration=66828000,QueueBufferDuration=276000,D/EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)D/EGL_emulation(4854):eglMakeCurrent:0xe3d47760:ver 2 0(tinfo 0xc6b24a30)I/OpenGLRenderer(4854):戴维!持续时间=6180ms;Flags=1, IntendedVsync=596431275408, Vsync=601081275222, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=601083214976, AnimationStart=601083253387, PerformTraversalsStart=601083255696, DrawStart=601096302305, SyncQueued=601333900000, SyncStart=601335418694, IssueDrawCommandsStart=601335535183, SwapBuffers= 602308827762,FrameCompleted=602612881859,DequeueBufferDuration=66828000,QueueBufferDuration=276000,D/EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)D/EGL_emulation(4854):eglMakeCurrent:0xe3d47760:ver 2 0(tinfo 0xc6b24a30)I/OpenGLRenderer(4854):戴维!持续时间=6180ms;Flags=1, IntendedVsync=596431275408, Vsync=601081275222, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=601083214976, AnimationStart=601083253387, PerformTraversalsStart=601083255696, DrawStart=601096302305, SyncQueued=601333900000, SyncStart=601335418694, IssueDrawCommandsStart=601335535183, SwapBuffers= 602308827762,FrameCompleted=602612881859,DequeueBufferDuration=66828000,QueueBufferDuration=276000,D/EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)
班级
import 'dart:convert';
Stocks stocksFromJson(String str) => Stocks.fromJson(json.decode(str));
String stocksToJson(Stocks data) => json.encode(data.toJson());
class Stocks {
String symbol;
String companyName;
String primaryExchange;
String calculationPrice;
int open;
int openTime;
double close;
int closeTime;
double high;
double low;
double latestPrice;
String latestSource;
String latestTime;
int latestUpdate;
int latestVolume;
dynamic iexRealtimePrice;
dynamic iexRealtimeSize;
dynamic iexLastUpdated;
double delayedPrice;
int delayedPriceTime;
double extendedPrice;
double extendedChange;
double extendedChangePercent;
int extendedPriceTime;
double previousClose;
int previousVolume;
int change;
double changePercent;
int volume;
dynamic iexMarketPercent;
dynamic iexVolume;
int avgTotalVolume;
dynamic iexBidPrice;
dynamic iexBidSize;
dynamic iexAskPrice;
dynamic iexAskSize;
int marketCap;
double peRatio;
double week52High;
int week52Low;
double ytdChange;
int lastTradeTime;
bool isUsMarketOpen;
Stocks({
this.symbol,
this.companyName,
this.primaryExchange,
this.calculationPrice,
this.open,
this.openTime,
this.close,
this.closeTime,
this.high,
this.low,
this.latestPrice,
this.latestSource,
this.latestTime,
this.latestUpdate,
this.latestVolume,
this.iexRealtimePrice,
this.iexRealtimeSize,
this.iexLastUpdated,
this.delayedPrice,
this.delayedPriceTime,
this.extendedPrice,
this.extendedChange,
this.extendedChangePercent,
this.extendedPriceTime,
this.previousClose,
this.previousVolume,
this.change,
this.changePercent,
this.volume,
this.iexMarketPercent,
this.iexVolume,
this.avgTotalVolume,
this.iexBidPrice,
this.iexBidSize,
this.iexAskPrice,
this.iexAskSize,
this.marketCap,
this.peRatio,
this.week52High,
this.week52Low,
this.ytdChange,
this.lastTradeTime,
this.isUsMarketOpen,
});
factory Stocks.fromJson(Map<String, dynamic> json) => Stocks(
symbol: json["symbol"],
companyName: json["companyName"],
primaryExchange: json["primaryExchange"],
calculationPrice: json["calculationPrice"],
open: json["open"],
openTime: json["openTime"],
close: json["close"].toDouble(),
closeTime: json["closeTime"],
high: json["high"].toDouble(),
low: json["low"].toDouble(),
latestPrice: json["latestPrice"].toDouble(),
latestSource: json["latestSource"],
latestTime: json["latestTime"],
latestUpdate: json["latestUpdate"],
latestVolume: json["latestVolume"],
iexRealtimePrice: json["iexRealtimePrice"],
iexRealtimeSize: json["iexRealtimeSize"],
iexLastUpdated: json["iexLastUpdated"],
delayedPrice: json["delayedPrice"].toDouble(),
delayedPriceTime: json["delayedPriceTime"],
extendedPrice: json["extendedPrice"].toDouble(),
extendedChange: json["extendedChange"].toDouble(),
extendedChangePercent: json["extendedChangePercent"].toDouble(),
extendedPriceTime: json["extendedPriceTime"],
previousClose: json["previousClose"].toDouble(),
previousVolume: json["previousVolume"],
change: json["change"],
changePercent: json["changePercent"].toDouble(),
volume: json["volume"],
iexMarketPercent: json["iexMarketPercent"],
iexVolume: json["iexVolume"],
avgTotalVolume: json["avgTotalVolume"],
iexBidPrice: json["iexBidPrice"],
iexBidSize: json["iexBidSize"],
iexAskPrice: json["iexAskPrice"],
iexAskSize: json["iexAskSize"],
marketCap: json["marketCap"],
peRatio: json["peRatio"].toDouble(),
week52High: json["week52High"].toDouble(),
week52Low: json["week52Low"],
ytdChange: json["ytdChange"].toDouble(),
lastTradeTime: json["lastTradeTime"],
isUsMarketOpen: json["isUSMarketOpen"],
);
Map<String, dynamic> toJson() => {
"symbol": symbol,
"companyName": companyName,
"primaryExchange": primaryExchange,
"calculationPrice": calculationPrice,
"open": open,
"openTime": openTime,
"close": close,
"closeTime": closeTime,
"high": high,
"low": low,
"latestPrice": latestPrice,
"latestSource": latestSource,
"latestTime": latestTime,
"latestUpdate": latestUpdate,
"latestVolume": latestVolume,
"iexRealtimePrice": iexRealtimePrice,
"iexRealtimeSize": iexRealtimeSize,
"iexLastUpdated": iexLastUpdated,
"delayedPrice": delayedPrice,
"delayedPriceTime": delayedPriceTime,
"extendedPrice": extendedPrice,
"extendedChange": extendedChange,
"extendedChangePercent": extendedChangePercent,
"extendedPriceTime": extendedPriceTime,
"previousClose": previousClose,
"previousVolume": previousVolume,
"change": change,
"changePercent": changePercent,
"volume": volume,
"iexMarketPercent": iexMarketPercent,
"iexVolume": iexVolume,
"avgTotalVolume": avgTotalVolume,
"iexBidPrice": iexBidPrice,
"iexBidSize": iexBidSize,
"iexAskPrice": iexAskPrice,
"iexAskSize": iexAskSize,
"marketCap": marketCap,
"peRatio": peRatio,
"week52High": week52High,
"week52Low": week52Low,
"ytdChange": ytdChange,
"lastTradeTime": lastTradeTime,
"isUSMarketOpen": isUsMarketOpen,
};
}
预先感谢您的帮助!
解决方案
看起来问题是.expand((data) => (data as List))
,看起来您的 API 返回一个 JSON 对象(地图)而不是 JSON 数组(列表)
我还发现了另一个细节,“AAPL”是 JSON 对象的一个键,其值是另一个 JSON 对象,如果你想将它的值映射到你的值,Class
你可以使用扩展来获取“AAPL”的值并传递它到你的工厂fromJSON
其他重要的事情是确保您尝试映射到您的键Class
存在于传递的 JSON 对象中。为避免动态键(可能不会出现的键)出现问题,您可以使用 Null-aware Operator
dart 中的 Null 感知运算符允许您根据值是否为 null 进行计算。它是较长表达式的简写。
一个让事情变得简单的建议,也许是不要使用 Streams,你可以重构你的代码,只使用 Future
const url = 'http://example.com/';
final response = await http.get(url);
final decodedResponse = json.decode(response);
final yourObject = Class.fromJSON(decodedResponse);
最后但并非最不重要的一点是,我强烈建议您看一下:
推荐阅读
- java - 为什么刷新jdbc swing表中的按钮后数据多次出现?
- xamarin.forms - CrossFirebasePushNotification.Current.RegisterForPushNotifications(); 抛出 NullReference iOS
- unity3d - 改变卡位
- python - BeautifulSoup 无法在 Div 之间获取文本
- c# - 如何在没有 azure 的情况下发布和部署多渠道机器人?
- fast-ai - Fastai 2020 课程 v4 windows 设置
- laravel - 如何使用多个 where 必须过滤 morphedByMany 关系?
- html - 创建一个不连接到任何其他边框的边框
- ruby-on-rails - Rails 6.1 参数编码设置为 ASCII-8BIT
- facebook - facebook messenger curl 请求返回