类扩展基类时无法生成 JSON 转换类

问题描述

我正在尝试创建一个 Model 并在 json_serializable 中使用 Flutter 包,但我面临的问题是当我尝试序列化或自动生成该类的代码时扩展基类。

所以在下面的课程中,如果我删除 AuthResponseData,它会抛出以下错误

无法为 fromJson 生成 user 代码

最后的最终用户数据用户

例如

@JsonSerializable()
class AuthResponseDataModel extends AuthResponseData {
  final UserDataModel user;
  final AccountDataModel accountData;

  AuthResponseDataModel(
    this.user,this.accountData,);

  factory AuthResponseDataModel.fromJson(Map<String,dynamic> json) =>
      _$AuthResponseDataModelFromJson(json);

  Map<String,dynamic> toJson() => _$AuthResponseDataModelToJson(this);
}

这是我的实体类 AuthResponseData

class AuthResponseData extends Equatable {
  late final UserData user;
  late final AccountData accountData;
  late final List<String> permissions;

  AuthResponseData({user,accountData,permissions});

  @override
  List<Object?> get props => [user,permissions];
}

最终,我想将 AuthResponseDataModel 排成 AuthResponse,但 json_serializer 不允许我这样做

解决方法

参考后解决

https://github.com/google/json_serializable.dart/issues/918

在类中添加以下内容

  @override
  UserDataModel get user => super.user as UserDataModel;
  @override
  AccountDataModel get accountData => super.accountData as AccountDataModel;