google / google/json_serializable.dart

JsonKey inheritance doesn't work with fromJson and toJson

Open
#1,057 3 comments 6 reactions 0 assignees View on GitHub
Type: enhancement
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.