Dart JsonSerialized 与抽象类

2024-02-21

我正在尝试为一个对象生成 json 辅助函数,该函数包含一个具有抽象类类型的列表,如下所示:

import 'package:json_annotation/json_annotation.dart';

import 'exercise-variations.a.dart';

part 'routine.model.g.dart';

@JsonSerializable()
class Routine {

  List<ExerciseRoutine> exercises;

  Routine();

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

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


    import 'package:json_annotation/json_annotation.dart';
    import 'exercise-variations.a.dart';

    part 'base-exercise-routine.g.dart';

    @JsonSerializable()
    class BaseExerciseRoutine implements ExerciseRoutine {
      int sets;

      BaseExerciseRoutine();

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

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

abstract class ExerciseRoutine {}

这样我得到这个错误:

[INFO] Running build...
[SEVERE] json_serializable:json_serializable on lib/test/routine.model.dart:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `exercises` because of type `ExerciseRoutine`.
None of the provided `TypeHelper` instances support the defined type.
package:dojohub_app_flutter/test/routine.model.dart:11:25
   ╷
11 │   List<ExerciseRoutine> exercises;
   │                         ^^^^^^^^^
   ╵
[INFO] Running build completed, took 1.2s

[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 92ms

[SEVERE] Failed after 1.3s
pub finished with exit code 1

这是有道理的,因为ExerciseRoutine没有实施toJson函数和一个fromJson工厂。也许我可以添加一个toJson函数到我的抽象类,但我如何修复丢失的fromJson工厂?


我通过编写自定义的 fromJson 和 toJson 函数解决了这个问题exercises Field

part 'routine.model.g.dart';

@JsonSerializable()
class Routine extends WorkoutRoutine {

  @JsonKey(fromJson: exercisesFromJson, toJson: exercisesToJson)
  List<ExerciseRoutine> exercises;

  Routine();

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

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

List<ExerciseRoutine> exercisesFromJson(List<dynamic> json) {
  return json.map((e) {
    return BaseExerciseRoutine.fromJson(e);
  }).toList();
}

List<dynamic> exercisesToJson(List<ExerciseRoutine> exercises) {
  return exercises.map((e) {
    switch (exercises.runtimeType) {
      case BaseExerciseRoutine:
        return (e as BaseExerciseRoutine).toJson();
      default:
        return null;
        break;
    }
  }).toList();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Dart JsonSerialized 与抽象类 的相关文章

随机推荐

  • LZW解压算法

    我正在为必须实现 LZW 压缩 解压缩的作业编写一个程序 我为此使用以下算法 压缩 w NIL while read a character k if wk exists in the dictionary w wk else add wk
  • 如何将按钮字体设置为 Marlett

    我正在尝试将按钮的字体设置为系统的 Marlett 字体 然而 虽然我手动设置了font face 但使用了其他字体 此外 当我使用字体对话框为该按钮选择字体时 Marlett 未列出 为什么会这样呢 如何在 NET Windows 窗体控
  • 第一个列表滚动在聚合物中结束后,铁滚动阈值永远不会执行

    我已经使用以下方法完成了iron list and iron scroll threshold为了在聚合物中实现无限滚动 但问题是 loadMoreDatairon scroll threshold在聚合物中第一个列表滚动结束后永远不会执行
  • Symfony 使用哪个单元测试框架?

    Symfony 使用哪个单元测试框架 Lime 还是 PHPUnit 使用它们有什么优点和缺点 在我看来 以下是我想到的一些事情 PHPUnit is more integrated with other tools like for in
  • MonoFoldable 有什么损失吗?

    单折叠 https hackage haskell org package mono traversable 1 0 0 1 docs Data MonoTraversable html t MonoFoldable in the 单通行
  • Laravel 5 MethodNotAllowedHttpException PUT

    我正在尝试更新用户 但是当我点击提交按钮时 Laravel 抛出以下错误 RouteCollection gt methodNotAllowed array GET HEAD POST 在 RouteCollection php 第 206
  • 开玩笑嘲笑参考错误

    我正在尝试使用以下模拟 const mockLogger jest fn jest mock myLoggerFactory gt type gt mockLogger 但是mockLogger会抛出引用错误 我知道笑话试图保护我免于超出模
  • 使用 jquery 禁用提交按钮

    我想在单击表单中的提交按钮后禁用它 以限制用户一次又一次地单击它 我用 jquery 尝试了这个 form submit function var formId this id if formId formId input type sub
  • 通过 PhpStorm 中的 Docker 容器使用 xdebug

    我读过一些关于此的文章 但没有一个对我的案例有帮助 或者只是忽略了缺失的部分 我无法使用 Docker 容器让 xdebug 在 PhpStorm 上工作 Docker compose yml version 2 services web
  • LEFT JOIN ON Google BigQuery 中的最近日期

    我有两个表 都有时间戳和更多数据 Table A name timestamp a data 1 2018 01 01 11 10 00 a 2 2018 01 01 12 20 00 b 3 2018 01 01 13 30 00 c T
  • Objective C 中的友元类

    我正在将 cpp 代码移植到 Objective C 中 In cpp我们可以添加一个类friend class到另一个类并使用其所有公共函数和变量 我知道Objective C does not support friend class概
  • 将 *ngFor 用于带有嵌套数组的 JSON 对象

    我有一个 JSON 对象 它具有多个级别的嵌套对象以及嵌套的对象数组 我想知道如何使用 Angular2 和 ngFor 迭代对象并最终打印出列出的内容 第一个 ngFor 有效 但下一个 ngFor 给我错误提示Cannot read p
  • 在 SQLite3 中插入​​和返回自动身份

    当我向数据库中插入一行时 我试图找出获取最后一个 ID 的最佳方法 它是一个基本库 它将异常和程序状态数据记录到 SQLite 数据库中 使用System Data SQLite 该库可以从控制台应用程序 表单应用程序 网站 服务 单线程
  • 使用codeigniter按每个类别的降序获取三个记录

    我有两个类别 我想获取每个类别的三个记录 后来我找到了这个链接使用 Codeigniter 活动记录模式进行 UNION 查询 https stackoverflow com questions 2040655 union query wi
  • 将 spring-boot-starter-parent 升级到版本 2.6.6 后,Java Spring Boot java.lang.NoClassDefFoundError [关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 我有一个 Spring Boot 应用程序 一直在使用 spring boot starter parent 版本 2
  • 如何从metrics-server获取Pod CPU和内存使用情况?

    我目前在 K8s 集群中安装并运行了指标服务器 利用 kubernetes python 库 我可以发出此请求来获取 pod 指标 from kubernetes import client api client client ApiCli
  • 没有默认构造函数?

    include
  • 如何防止 Visual Studio 在 Web 项目中“发布”XML 文档文件?

    Note 这个问题类似于如何防止在发布模式构建中复制 XML 文档文件 https stackoverflow com questions 3980958 how to prevent the copy of xml documentati
  • 对分组表进行数学运算

    我的问题不在于真正的编程语言 我有一个 ABAP 语言练习 但该语言不是很重要 无论如何 我有一张桌子 我需要计算该职位的总成本 显然是在选择之后 然后 该表将按两个字段 MATNR 和 BUKRS 进行分组 因此我需要知道每个组的头寸总成
  • Dart JsonSerialized 与抽象类

    我正在尝试为一个对象生成 json 辅助函数 该函数包含一个具有抽象类类型的列表 如下所示 import package json annotation json annotation dart import exercise variat