我有以下两个类,其中一个类是从另一个类扩展而来的:
@JsonSerializable(nullable: true)
class Response {
final String responseCode;
final String responseMessage;
final String errorLog;
Response({this.errorLog, this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
…………………………………………………………………………………………………………………………………… ......
@JsonSerializable(nullable: false)
class Verify extends Response {
Data data;
Verify({
this.data,
});
factory Verify.fromJson(Map<String, dynamic> json) => _$VerifyFromJson(json);
Map<String, dynamic> toJson() => _$VerifyToJson(this);
}
每当我试图从验证 clasit 中读取 响应 类属性时,总是为空
那么请如何实现这一目标?
最佳答案
这个我通过在验证类构造函数中将参数传递给 super 来解决的
@JsonSerializable()
class VerifyResponse extends Response {
Data data;
VerifyResponse({
this.data,
String responseCode,
String responseMessage,
}) : super(responseCode: responseCode, responseMessage: responseMessage);
factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
_$VerifyResponseFromJson(json);
Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
}
对于响应类,它保持不变@JsonSerializable()
class Response {
final String responseCode;
final String responseMessage;
Response({this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
这有点烦人,但就是这样。关于带有继承类的 flutter Dart JsonSerializable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62144987/