【发布时间】:2021-07-01 12:29:23
【问题描述】:
我正在尝试在用户输入电子邮件和密码后获取用户信息。我正在使用的 api 返回用户的额外信息,所以我试图从这些信息开始。
我正在尝试解析这个 json:
[
{
"_user": {
"id": "id-here",
"name": "Mobile",
"email": "mobile.user@asd.com",
"photo": null,
"title": null,
"surname": "User",
"bg_photo": null,
"isactive": true,
"password": "123456789",
"username": "mobileuser",
"checkInfo": true,
"role_type": "asd",
"profession": null,
"isemailverify": false
},
"tokens": {
"accessToken": "someTokenhere",
"refreshToken": "anotherOne"
}
}
]
这些是我的模型:
class User {
User({
this.user,
this.tokens,
});
UserClass user;
Tokens tokens;
factory User.fromJson(Map<String, dynamic> json){
return User(
user: UserClass.fromJson(json["_user"]),
tokens: Tokens.fromJson(json["tokens"]),
);
}
}
class Tokens {
Tokens({
this.accessToken,
this.refreshToken,
});
String accessToken;
String refreshToken;
factory Tokens.fromJson(Map<String, dynamic> json) => Tokens(
accessToken: json["accessToken"],
refreshToken: json["refreshToken"],
);
}
class UserClass {
UserClass({
this.id,
this.name,
this.email,
this.photo,
this.title,
this.surname,
this.bgPhoto,
this.isactive,
this.password,
this.username,
this.checkInfo,
this.roleType,
this.profession,
this.isemailverify,
});
String id;
String name;
String email;
String photo;
String title;
String surname;
String bgPhoto;
bool isactive;
String password;
String username;
bool checkInfo;
String roleType;
String profession;
bool isemailverify;
factory UserClass.fromJson(Map<String, dynamic> json) => UserClass(
id: json["id"],
name: json["name"],
email: json["email"],
photo: json["photo"],
title: json["title"],
surname: json["surname"],
bgPhoto: json["bg_photo"],
isactive: json["isactive"],
password: json["password"],
username: json["username"],
checkInfo: json["checkInfo"],
roleType: json["role_type"],
profession: json["profession"],
isemailverify: json["isemailverify"],
);
}
这是我发送电子邮件、密码和获取用户数据的部分:
Future<User> checkUserExist(String email, String password) async {
final response = await http.post(
Uri.https('SomeApi', 'Route'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'email': email,
'password': password
}),
);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception(jsonDecode(response.body));
}
}
这是给我错误的部分
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
我打印了响应正文,它给了我我想要的 - 字符串 - 但 jsonDecode 返回一个列表,所以我不能使用它。我怎样才能解决这个问题?提前致谢。
【问题讨论】: