首页 > 解决方案 > 使用嵌套api解析模型类中的JSON以登录flutter?

问题描述

我正在尝试下面的代码

Future<LoginModel> user(
          String mobile, String standardId, String mediumId) async {
        String loginUrl = "$baseUrl/user/login";
        var body = jsonEncode({
          'mobile': mobile,
          'standard_id': standardId,
          'medium_id': mediumId,
        });
    
        final response = await http.post(
          Uri.parse(loginUrl),
          headers: <String, String>{'Content-Type': 'application/json'},
          body: body.toString(),
        );
        if (response.statusCode == 200) {
          var userMap = jsonDecode(response.body);
          var userData = LoginModel.fromJson(userMap);
          print(userData);
        } else {}
        return null!;
      }

但我收到以下错误:

_TypeError (type 'Null' is not a subtype of type 'Map<String, dynamic>') 异常,在这一行 ==>> user: User.fromJson(json["user"]),来自下面的模型类。

这是我的模型代码加上 json 映射

 ```// To parse this JSON data, do
    //
    //     final loginModel = loginModelFromJson(jsonString);
    
    import 'dart:convert';
    
    LoginModel loginModelFromJson(String str) =>
        LoginModel.fromJson(json.decode(str));
    
    String loginModelToJson(LoginModel data) => json.encode(data.toJson());
    
    class LoginModel {
      LoginModel({
        required this.success,
        required this.user,
        required this.planId,
        required this.msg,
      });
    
      int success;
      User user;
      String planId;
      String msg;
    
      factory LoginModel.fromJson(Map<String, dynamic> json) => LoginModel(
            success: json["success"],
            user: User.fromJson(json["user"]),
            planId: json["plan_id"],
            msg: json["msg"],
          );
    
      Map<String, dynamic> toJson() => {
            "success": success,
            "user": user.toJson(),
            "plan_id": planId,
            "msg": msg,
          };
    }
    
    class User {
      User({
        required this.userId,
        required this.name,
        required this.mobile,
        required this.email,
        required this.standardId,
        required this.mediumId,
        required this.location,
        required this.avatar,
        required this.deviceId,
        required this.createdAt,
        required this.updatedAt,
      });
    
      String userId;
      String name;
      String mobile;
      String email;
      String standardId;
      String mediumId;
      String location;
      String avatar;
      String deviceId;
      DateTime createdAt;
      DateTime updatedAt;
    
      factory User.fromJson(Map<String, dynamic> json) => User(
            userId: json["user_id"] ?? null,
            name: json["name"] ?? null,
            mobile: json["mobile"] ?? null,
            email: json["email"] ?? null,
            standardId: json["standard_id"] ?? null,
            mediumId: json["medium_id"] ?? null,
            location: json["location"] ?? null,
            avatar: json["avatar"] ?? null,
            deviceId: json["device_id"] ?? null,
            createdAt: DateTime.parse(json["created_at"] ?? null),
            updatedAt: DateTime.parse(json["updated_at"] ?? null),
          );
    
      Map<String, dynamic> toJson() => {
            "user_id": userId,
            "name": name,
            "mobile": mobile,
            "email": email,
            "standard_id": standardId,
            "medium_id": mediumId,
            "location": location,
            "avatar": avatar,
            "device_id": deviceId,
            "created_at":
                "${createdAt.year.toString().padLeft(4, 
    '0')}-${createdAt.month.toString().padLeft(2, '0')}-${createdAt.day.toString().padLeft(2, 
    '0')}",
            "updated_at":
                "${updatedAt.year.toString().padLeft(4, 
    '0')}-${updatedAt.month.toString().padLeft(2, '0')}-${updatedAt.day.toString().padLeft(2, 
    '0')}",
          };
    }

我缺少什么或我的代码有什么问题?

标签: flutter

解决方案


试试这可能是接收到的 json 中缺少某些属性。

// To parse this JSON data, do
//
//     final loginModel = loginModelFromJson(jsonString);

import 'dart:convert';

LoginModel loginModelFromJson(String str) => LoginModel.fromJson(json.decode(str));

String loginModelToJson(LoginModel data) => json.encode(data.toJson());

class LoginModel {
    LoginModel({
        this.success,
        this.user,
        this.planId,
        this.msg,
    });

    int success;
    User user;
    String planId;
    String msg;

    factory LoginModel.fromJson(Map<String, dynamic> json) => LoginModel(
        success: json["success"] == null ? null : json["success"],
        user: json["user"] == null ? null : User.fromJson(json["user"]),
        planId: json["plan_id"] == null ? null : json["plan_id"],
        msg: json["msg"] == null ? null : json["msg"],
    );

    Map<String, dynamic> toJson() => {
        "success": success == null ? null : success,
        "user": user == null ? null : user.toJson(),
        "plan_id": planId == null ? null : planId,
        "msg": msg == null ? null : msg,
    };
}

class User {
    User({
        this.userId,
        this.name,
        this.mobile,
        this.email,
        this.standardId,
        this.mediumId,
        this.location,
        this.avatar,
        this.deviceId,
        this.createdAt,
        this.updatedAt,
    });

    String userId;
    String name;
    String mobile;
    String email;
    String standardId;
    String mediumId;
    String location;
    String avatar;
    String deviceId;
    DateTime createdAt;
    DateTime updatedAt;

    factory User.fromJson(Map<String, dynamic> json) => User(
        userId: json["user_id"] == null ? null : json["user_id"],
        name: json["name"] == null ? null : json["name"],
        mobile: json["mobile"] == null ? null : json["mobile"],
        email: json["email"] == null ? null : json["email"],
        standardId: json["standard_id"] == null ? null : json["standard_id"],
        mediumId: json["medium_id"] == null ? null : json["medium_id"],
        location: json["location"] == null ? null : json["location"],
        avatar: json["avatar"] == null ? null : json["avatar"],
        deviceId: json["device_id"] == null ? null : json["device_id"],
        createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
        updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "user_id": userId == null ? null : userId,
        "name": name == null ? null : name,
        "mobile": mobile == null ? null : mobile,
        "email": email == null ? null : email,
        "standard_id": standardId == null ? null : standardId,
        "medium_id": mediumId == null ? null : mediumId,
        "location": location == null ? null : location,
        "avatar": avatar == null ? null : avatar,
        "device_id": deviceId == null ? null : deviceId,
        "created_at": createdAt == null ? null : "${createdAt.year.toString().padLeft(4, '0')}-${createdAt.month.toString().padLeft(2, '0')}-${createdAt.day.toString().padLeft(2, '0')}",
        "updated_at": updatedAt == null ? null : "${updatedAt.year.toString().padLeft(4, '0')}-${updatedAt.month.toString().padLeft(2, '0')}-${updatedAt.day.toString().padLeft(2, '0')}",
    };
}

推荐阅读