这是我要解析的json文件:
{
"Meta Data": {
"1. Information": "Weekly Adjusted Prices and Volumes",
"2. Symbol": "MSFT",
"3. Last Refreshed": "2020-03-25",
"4. Time Zone": "US/Eastern"
},
"Weekly Adjusted Time Series": {
"2020-03-25": {
"1. open": "137.0100",
"2. high": "154.3300",
"3. low": "132.5200",
"4. close": "146.9200",
"5. adjusted close": "146.9200",
"6. volume": "235583286",
"7. dividend amount": "0.0000"
},
"2020-03-20": {
"1. open": "140.0000",
"2. high": "150.1500",
"3. low": "135.0000",
"4. close": "137.3500",
"5. adjusted close": "137.3500",
"6. volume": "421347734",
"7. dividend amount": "0.0000"
},
}
我只是想获取日期、打开和关闭。我尝试在网上查找东西,但仍然无法做到这一点。
这是我的 TimeSeries 类:
class TimeSeries {
final String date;
final double open;
final double close;
TimeSeries({this.date, this.open, this.close});
factory TimeSeries.fromJson(Map<String, dynamic> json) {
return TimeSeries(
date: json[''],
open: double.parse(json['1. open']),
close: double.parse(json['4. close']),
);
}
}
这些是我现在的功能:
Future getTimeSeries(String stock) async {
print("Starting get request");
http.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo").then((res){
print("received response.");
var resObj = json.decode(res.body);
}).catchError((e) {
print("Failed to get response.");
});
}
最佳答案
试试这个。
class TimeSeries {
final String date;
final double open;
final double close;
TimeSeries({this.date, this.open, this.close});
factory TimeSeries.fromJson(Map<String, dynamic> json, String indexDate) {
return TimeSeries(
date: indexDate,
open: double.parse(json["Weekly Adjusted Time Series"][indexDate]['1. open']),
close: double.parse(json["Weekly Adjusted Time Series"][indexDate]['4. close']),
);
}
}
并且您可以按如下方式调用构造函数
List<TimeSeries> datesList(json) {
List<TimeSeries> dates;
for (date in json["Weekly Adjusted Time Series"]) {
dates.add(TimeSeries.fromJson(json, date));
}
return dates;
}
关于android - Flutter:如何在 dart 上解析 json 嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60859639/