【问题标题】:flutter dart JsonSerializable with inherited class带有继承类的颤振飞镖JsonSerializable
【发布时间】:2020-09-20 12:10:42
【问题描述】:

我有以下两个类,其中一个类从另一个类扩展,如下所示:

@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);
}

每当我尝试从验证类中读取 response 类属性时,它始终为空。

那么请问如何实现呢?

【问题讨论】:

  • datacontractjsonserializer 是一个 .NET 组件,可以将 .NET 对象直接序列化为 JSON 数据。由于您使用的是颤振和飞镖,而不是 c# 或任何其他 .Net 语言,我删除了标签。

标签: flutter inheritance dart jsonserializer


【解决方案1】:

我已经通过在验证类构造函数中将参数传递给 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);
}

这有点烦人,但就是这样。

【讨论】:

    【解决方案2】:

    您应该从响应类中删除 'final' 关键字

    @JsonSerializable(nullable: true)
        class Response {
          String responseCode;
          String responseMessage;
          String errorLog;
          Response({this.errorLog, this.responseCode, this.responseMessage});
          factory Response.fromJson(Map<String, dynamic> json) =>
               _$ResponseFromJson(json);
    }
    

    【讨论】:

    • 删除基类成员中的“final”关键字为我修复了它。谢谢!
    • 为什么?删除final有什么意义。这只意味着这个值将从合同中获取
    【解决方案3】:

    它通过将super(); 显式添加到子类的构造函数来工作。

    @JsonSerializable()
    class VerifyResponse extends Response {
      Data data;
    
      VerifyResponse({
        this.data,
        String responseCode,
        String responseMessage,
        //No need to list all parent class properties
        }) : super();
    
      factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
          _$VerifyResponseFromJson(json);
    
      Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 1970-01-01
      • 2022-11-12
      • 2019-06-03
      • 2020-12-25
      • 2020-11-05
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多