【问题标题】:Generate fromJson code for non valid json type为无效的 json 类型生成 fromJson 代码
【发布时间】:2021-07-30 20:59:09
【问题描述】:

我正在使用freezed.

我的代码如下所示:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'key_state.freezed.dart';
part 'key_state.g.dart';

@freezed
class KeyState with _$KeyState {
  factory KeyState({
    CancelToken? token,
    // ...
  }) = _KeyState;

  factory KeyState.initial() => KeyState();

  factory KeyState.fromJson(Map<String, dynamic> json) =>
      _$KeyStateFromJson(json);
}

这是来自https://github.com/flutterchina/dio/blob/master/dio/lib/src/cancel_token.dart 的CancelToken 类

这不起作用。

错误:

Could not generate `fromJson` code for `token`.
To support the type `CancelToken` you can:
* Use `JsonConverter`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
* Use `JsonKey` fields `fromJson` and `toJson`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
package:flutter_app/redux/state/key_state.freezed.dart:114:22

我该怎么做?

【问题讨论】:

标签: flutter flutter-freezed


【解决方案1】:

错误告诉你 CancelToken 类不能直接转换为 JSON。您的选择是:

  1. 构建一个将您的 KeyState 类手动转换为 JSON 表示的服务类。

  2. 在您的项目中为 CancelToken 类创建一个扩展方法,将 fromJson 和 toJson 方法添加到其中。 https://dart.dev/guides/language/extension-methods

  3. 从 Github 分叉代码,自己将转换方法添加到 CancelToken 类,并在 pubspec.yaml 文件中引用您的 repo。 (另外,提交拉取请求以将您的更改合并到原始存储库中)

您还需要为依赖类型(如 DioError、RequestOptions、Response)添加类似的转换方法。

【讨论】:

  • 是的,我明白了,我不知道该怎么做。您能否分享如何构建一个服务类,将您的 KeyState 类手动转换为 JSON 表示。
  • 你能发一个2号的例子吗?谢谢
  • 有什么解决方法吗?
猜你喜欢
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2011-01-24
相关资源
最近更新 更多