gpt4 book ai didi

arrays - 如何从JSON传递List 到List

转载 作者:行者123 更新时间:2023-12-03 03:59:00 25 4
gpt4 key购买 nike

我有一个从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;

关于arrays - 如何从JSON传递List <dynamic>到List <MyModel>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com