Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with parsing Json data in flutter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading