json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

JsonKey inheritance doesn't work with fromJson and toJson

Open liranzairi opened this issue 4 years ago • 3 comments

This is continuing https://github.com/google/json_serializable.dart/issues/575 since that issue has been closed.

When extending JsonKey, fromJson and toJson don't work. For example, if I create this class:

class MyJsonKey extends JsonKey {
  const MyJsonKey({
    bool? required,
    Function? fromJson,
    Function? toJson,
  }) : super(
          required: required != false,
          disallowNullValue: true,
          fromJson: fromJson,
          toJson: toJson,
        );
}

And use it in my json object:

@JsonSerializable()
class MyObject {
  @MyJsonKey(fromJson: /* some static func */, toJson: /* some static func */)
  final DifferentClass differentClass;

  const MyObject(this.differentClass);
}

Then build_runner will fail:

Could not generate `fromJson` code for `differentClass`.
To support the type `DifferentClass` 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

Output of dart --version: Dart SDK version: 2.14.4 (stable) (Wed Oct 13 11:11:32 2021 +0200) on "macos_x64" Using versions: json_serializable 6.1.0 build_runner 2.1.5 json_annotation 4.4.0

liranzairi avatar Dec 02 '21 17:12 liranzairi

@kevmoo Hi, are there any plans to support this? Thanks 😊

liranzairi avatar Apr 05 '22 16:04 liranzairi

I have this issue too

hosseinshaya avatar May 31 '22 09:05 hosseinshaya

It's likely gnarly to figure this out. I can look.

kevmoo avatar Dec 21 '22 23:12 kevmoo