我正在读取带有几个不同数组的json。因此,我想将其映射到其单独的模型列表。因此,我首先为例如如下。
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'],
);
}
}
我设法调用了我的api,以下是我的json结果看起来不完整的样子,
"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": [
..........
]
下面是我写汇总数组的方式。
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());
}
我最终得到type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
答案 0 :(得分:1)
这是因为返回的响应包含Map列表而不是map。
更改您的行Summary summary1 = new Summary.fromJson(fullJson['Summary']);
到Summary summary1 = new Summary.fromJson(fullJson['Summary'][i]);
其中,我的值可以是0到“摘要”中的对象数减去1之间的任何值。
要获取Summary
个对象的完整列表,请执行以下操作:
int totalSummaryCount = fullJson['totalSummary'];
List<Summary> list = new List<Summary>.generate(totalSummaryCount, (index)=>Summary.fromJson(fullJson['Summary'][index]));