这是我的长度为1的JSON数组的代码,该数组返回长度为0的结果:
class profilInfo {
final List<information> result;
profilInfo._({ this.result});
factory profilInfo.fromJson(Map jsonMap) {
return new profilInfo._(
result : (jsonMap['result'] as List).map((i) =>
information.fromJson(i)).toList()
);
}
}
class information{
final String firstname;
final String country;
final String city;
final String about;
final String profilephoto;
information._({
this.firstname,this.country,this.about,this.city,this.profilephoto});
factory information.fromJson(Map jsonMap) {
return new information._(
firstname : jsonMap['first_name'],
country : jsonMap['country'],
city : (jsonMap['city']),
about : (jsonMap['about']),
profilephoto : (jsonMap['profile_photo']),
);
}
}
我有一个JSON文件:
{
"status": 200,
"result": [
{
"username": "mohammad",
"password": "202cb962ac59075b964b07152d234b70",
"create_date": "2019-08-13T08:53:24.997Z",
"modify_date": "2019-08-13T08:53:24.997Z",
"last_pay_date": null,
"first_name": "mohammad reza shabani",
"last_name": " ",
"country": "usa",
"city": "alai",
"phone": "09120564589",
"users_id": [],
"profile_photo": "",
"about": "",
"_id": "5d527a84abe6713aacc62453",
"__v": 0
}
]
}
我收到此错误:
[ERROR:flutter / lib / ui / ui_dart_state.cc(148)]未处理的异常:RangeError(索引):无效值:有效值范围为空:0
答案 0 :(得分:1)
尝试以下代码:-
class profilInfo {
final List<information> result;
profilInfo._({this.result});
factory profilInfo.fromJson(Map jsonMap) {
List<information> informationList = new List();
var infoList = jsonMap['result'] as List;
informationList =
infoList.map((i) => information.fromJson(i)).toList();
return new profilInfo._(result: informationList);
}
}
class information {
final String firstname;
final String country;
final String city;
final String about;
final String profilephoto;
information._(
{this.firstname, this.country, this.about, this.city, this.profilephoto});
factory information.fromJson(Map<String, dynamic> jsonMap) {
return new information._(
firstname: jsonMap['first_name'],
country: jsonMap['country'],
city: jsonMap['city'],
about: jsonMap['about'],
profilephoto: jsonMap['profile_photo'],
);
}
}
答案 1 :(得分:0)
我建议您使用这个很棒的网站quik_types 要创建将json对象转换为数据模型所需的类和函数,只需给他一个需要转换的json对象,其余的就交给他。它更快,输入更安全,因此可以节省许多不必要的工作和时间