Json 未处理的异常:类型';列表<;动态>';不是类型为';列表<;模型>';
我试图解析从在线API获取的Json数据,但却遇到了标题中提到的错误。我看了类似的问题,但找不到解决办法 以下是相关代码:Json 未处理的异常:类型';列表<;动态>';不是类型为';列表<;模型>';,json,flutter,Json,Flutter,我试图解析从在线API获取的Json数据,但却遇到了标题中提到的错误。我看了类似的问题,但找不到解决办法 以下是相关代码: class Model { final double a; final double b; final String s; Model._({this.a, this.b, this.s}); factory Model.fromJson(Map<String, dynamic>
class Model {
final double a;
final double b;
final String s;
Model._({this.a, this.b, this.s});
factory Model.fromJson(Map<String, dynamic> json) {
return new Model._(
a: json['a'],
b: json['b'],
s: json['s'],
);
}
}
void fetchPairValue() async {
final response = await http.get('https://api.1forge.com/quotes?pairs=USD/TRY,EUR/USD,EUR/TRY,CAD/TRY,GBP/TRY,AUD/TRY,JPY/TRY,CHF/TRY,AED/TRY,USD/QAR,USD/BGN,DKK/TRY,USD/SAR,USD/CNY,USD/RUB,NOK/TRY,SEK/TRY'
'&api_key=KatWbQa9sDFmYQ25LmtAMlGau5xKSWIe');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
List<Model> list = json.decode(response.body).map((data) => Model.fromJson(data))
.toList();
setState(() {
currencyPair[0][1] = round_to_4(list[0].b).toString();
currencyPair[0][2] = round_to_4(list[0].a).toString();
for (int i = 1; i < currencyPair.length; i++) {
if(list[i].s.startsWith('USD'))
{
currencyPair[i][1] = round_to_4(list[i].b/list[1].b).toString();
currencyPair[i][2] = round_to_4(list[i].a/list[1].a).toString();
}
else {
currencyPair[i][1] = round_to_4(list[i].b).toString();
currencyPair[i][2] = round_to_4(list[i].a).toString();
}
}
});
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
如何修复?谢谢。您需要将泛型类型添加到映射函数中:
List<Model> list = json
.decode(response)
.map<Model>((data) => Model.fromJson(data))
.toList();
List=json
.解码(响应)
.map((数据)=>Model.fromJson(数据))
.toList();
List<Model> list = json
.decode(response)
.map<Model>((data) => Model.fromJson(data))
.toList();