在flutter中解析Json数据的问题

nlejzf6q  于 2023-05-29  发布在  Flutter
关注(0)|答案(1)|浏览(135)

我正在尝试解析下面的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'

r6l8ljro

r6l8ljro1#

你的问题就在这里;

LoginResponse response = jsonDecode(loginResponse.body);

应该像下面这样改变;

Map<String, dynamic> parsedData = jsonDecode(loginResponse.body);
UserData userData = UserData.fromJson(parsedData);

并且,根据所提供的JSON,userId不是String类型;它是int类型。因此,您应该在UserData类中将“String”更改为“int”。

相关问题