[我有一个从API检索数据的应用程序,我以列表的形式接收数据,当我打印它时,我可以看到正常的数据。
[
{
"1": "MaxMilyin",
"2": "409733",
"3": "1130794"
},
{
"1": "HippopotamusRex",
"2": "346742",
"3": "1204932"
},
...
]
[当我尝试将列表传递到模型列表时,我只会得到:
[Instance of 'TopTenUsersModel', Instance of 'TopTenUsersModel', ...]
这是我的模型类,我使用此site生成了该类:
class TopTenUsersModel {
String s1;
String s2;
String s3;
TopTenUsersModel({this.s1, this.s2, this.s3});
TopTenUsersModel.fromJson(Map<String, dynamic> json) {
s1 = json['1'];
s2 = json['2'];
s3 = json['3'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['1'] = this.s1;
data['2'] = this.s2;
data['3'] = this.s3;
return data;
}
}
这是我将数据作为模型返回的方法。
static Future<List<TopTenUsersModel>> getTopTenUsers() async{
try{
print("INICIANDO CONEXÃO COM A API...");
var response = await client.get(
Constants.BASE_URL + Constants.getTopTenUsers + Constants.AUTH
);
//print("PRINT RESPONSE NETWORK UTIL: ${response.body}");
// Here I can see the data ok!
List<dynamic> list = json.decode(response.body) as List;
// Here I get 'Instance of 'TopTenUsersModel''
return (json.decode(response.body) as List)
.map((item) => TopTenUsersModel.fromJson(item))
.toList();
} on SocketException catch (e){
throw (e.message);
} finally {
client.close();
}
}
您应通过以下方式实施
模型类
class TopTenUsersModelResponse {
final List<TopTenUsersModel> list;
TopTenUsersModelResponse({
this.list,
});
factory TopTenUsersModelResponse.fromJson(List<dynamic> parsedJson) {
List<TopTenUsersModel> list = new List<TopTenUsersModel>();
list = parsedJson.map((i) => TopTenUsersModel.fromJson(i)).toList();
return new TopTenUsersModelResponse(list: list);
}
}
替换
List<dynamic> list = json.decode(response.body) as List;
// Here I get 'Instance of 'TopTenUsersModel''
return (json.decode(response.body) as List)
.map((item) => TopTenUsersModel.fromJson(item))
.toList();
作者
final List parsed = json.decode(response.body);
List<TopTenUsersModel> responseModelList = new TopTenUsersModelResponse.fromJson(parsed).list;