I am trying to parse the below Json data:
{
"userData": {
"userId": 29922,
"applicationId": 28,
"siteId": 66
},
"verificationStatus": true
}
My Model Class:
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');
But I am getting Unhandled Exception: type '_Map<String, dynamic>' is not a subtype of type 'LoginResponse'
>Solution :
You problem is here;
LoginResponse response = jsonDecode(loginResponse.body);
Should change like below;
Map<String, dynamic> parsedData = jsonDecode(loginResponse.body);
UserData userData = UserData.fromJson(parsedData);
And also, according to the provided JSON, the userId is not of type String; it is of type int. Therefore, you should change ‘String’ to ‘int’ in the UserData class.