作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个从API检索数据的应用程序,我以列表的形式接收数据,当我打印它时,可以看到数据。
[
{
"1": "MaxMilyin",
"2": "409733",
"3": "1130794"
},
{
"1": "HippopotamusRex",
"2": "346742",
"3": "1204932"
},
...
]
[Instance of 'TopTenUsersModel', Instance of 'TopTenUsersModel', ...]
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;
关于arrays - 如何从JSON传递List <dynamic>到List <MyModel>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715593/
我是一名优秀的程序员,十分优秀!