我正在尝试解析下面的JSON数据:
{
"userData": {
"userId": 29922,
"applicationId": 28,
"siteId": 66
},
"verificationStatus": true
}
我的模型类:
import 'dart:convert';
class LoginResponse {
final UserData userData;
final bool verificationStatus;
LoginResponse({required this.userData, required this.verificationStatus});
factory LoginResponse.fromJson(Map<String, dynamic> json) {
return LoginResponse(
verificationStatus: json['verificationStatus'] as bool,
userData: UserData.fromJson(json['userData']) ,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userData'] = this.userData;
data['verificationStatus'] = this.verificationStatus;
return data;
}
}
class UserData{
final String userId;
UserData({required this.userId});
factory UserData.fromJson(Map<String, dynamic> json) {
return UserData(
userId: json['userId'] as String
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
return data;
}
}
main.dart
//loginResponse.body is the Json data
http.Response loginResponse = await postRequest();
LoginResponse response = jsonDecode(loginResponse.body);
print('status:>>$response.verificationStatus');
print('userId:>>$response.userData.userId');
但我得到了Unhandled Exception: type '_Map<String, dynamic>' is not a subtype of type 'LoginResponse'
1条答案
按热度按时间r6l8ljro1#
你的问题就在这里;
应该像下面这样改变;
并且,根据所提供的JSON,userId不是String类型;它是int类型。因此,您应该在UserData类中将“String”更改为“int”。