user3808307
user3808307

Reputation: 1549

Generate fromJson code for non valid json type

I am using freezed.

My code looks like this:

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

This is the CancelToken class from https://github.com/flutterchina/dio/blob/master/dio/lib/src/cancel_token.dart

This does not work.

Errors:

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

How do I do this?

Upvotes: 2

Views: 894

Answers (1)

Phil Cazella
Phil Cazella

Reputation: 854

The error is telling you that the CancelToken class cannot be converted to JSON directly. Your options are:

  1. Build a service class that converts your KeyState class into a JSON representation manually.

  2. Create an extension method for the CancelToken class in your project, which adds the fromJson and toJson methods to it. https://dart.dev/guides/language/extension-methods

  3. Fork the code from Github, add the conversion methods to the CancelToken class yourself, and reference your repo in your pubspec.yaml file. (also, submit a pull request to merge your changes into the original repo)

You will also need to add similar conversion methods for dependant types like DioError, RequestOptions, Response.

Upvotes: 2

Related Questions