Bar*_*ban 5 inheritance jsonserializer dart flutter
我有以下两个类,其中一个类是从另一个类扩展而来的:
@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);
}
Run Code Online (Sandbox Code Playgroud)
………………………………………………………………………………………………………………………………………………………… ......
@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);
}
Run Code Online (Sandbox Code Playgroud)
每当我试图从验证类读取响应类属性时,总是为空
那么请如何实现这一目标?
Bar*_*ban 15
我通过将参数传递给验证类构造函数中的 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);
}
Run Code Online (Sandbox Code Playgroud)
对于响应类,它保持不变
@JsonSerializable()
class Response {
final String responseCode;
final String responseMessage;
Response({this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)
这有点烦人,但就是这样。