arrays - Flutter mapping json to model array 'List' is not a subtype of type 'Map'`
问题描述
I am reading a json with few different arrays. So I want to map it to its individual model list. Thus first I created the list for e.g. as below.
class Summary {
final String totalDuration;
final String totalMileage;
//final String fleetID;
Summary({this.totalDuration, this.totalMileage});
Map<String, dynamic> toJson() => {
'totalDuration': totalDuration,
'totalMileage': totalMileage,
};
factory Summary.fromJson(Map<String, dynamic> json) {
return new Summary(
totalDuration: json['totalDuration'],
totalMileage: json['totalMileage'],
);
}
}
I have managed to call my api and below is how my json results look like its not the complete one as I wanted to make it brief.
"totalSummary": 6,
"Summary": [
{
"totalDuration": "2549",
"totalMileage": "22.898"
},
{
"totalDuration": "11775",
"totalMileage": "196.102"
},
{
"totalDuration": "17107",
"totalMileage": "232.100"
},
{
"totalDuration": "34870",
"totalMileage": "177.100"
},
{
"totalDuration": "33391",
"totalMileage": "168.102"
},
{
"totalDuration": "13886",
"totalMileage": "77.398"
}
],
"totalDetails": 16,
"details": [
..........
]
Below is how I wrote to populate the summary array.
final fullJson = await NetworkUtils.post(url,token,data);
print("fullJson"+fullJson.toString());
try{
Summary summary1 = new Summary.fromJson(fullJson['Summary']);
print(summary1.totalMileage);
}
catch(Err){
print("Erro is at"+Err.toString());
}
I end up getting type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
解决方案
这是因为返回的响应包含 Map 的 List 而不是 map 。
改变你的线路Summary summary1 = new Summary.fromJson(fullJson['Summary']);
至Summary summary1 = new Summary.fromJson(fullJson['Summary'][i]);
其中 i 可以是 0 到 Summary 中的对象数减一之间的任何值。
要获取Summary
对象的完整列表,请执行以下操作:
int totalSummaryCount = fullJson['totalSummary'];
List<Summary> list = new List<Summary>.generate(totalSummaryCount, (index)=>Summary.fromJson(fullJson['Summary'][index]));
推荐阅读
- http - 无法使用邮递员发送发布请求
- c# - 检查文件系统内的控制更改 Watcher Changed 事件导致异常
- mysql - MySql 数据库到 Microsoft Server Managemant Studio
- mysql - Mysql RDS 认证安全
- javascript - 切换背景图像 MVC
- java - Jama Matrix 打印机错误
- android - 在 OneSignal 推送通知上打开不同的活动
- date - ExtJS:日期字段将日期写回一天?
- javascript - 在 HTML/CSS/JS 中修复缩放时间线
- .net - 如何在 F# 中声明可以通过 WebJob 的 JobHost.CallAsync 调用的函数?