google / google/json_serializable.dart
Generics complicate self-referential class structure
- Dominant language
- Dart
- Stars
- 1.6k
- Forks
- 461
- Avg merge
- 45m
- Merged PRs (30d)
- 1
Description
The following code builds, but see the comment for which critical information has to be removed for said build to succeed:
```dart
class Base {
const Base();
}
class BaseConverter extends JsonConverter> {
const BaseConverter();
@override
Map toJson(Base object) => {};
@override
Base fromJson(Map json) => Base();
}
@JsonSerializable()
class Data extends Base {
Data({
required this.data,
required this.name,
});
factory Data.fromJson(Map json) => _$DataFromJson(json);
final String name;
@BaseConverter()
// Ideally, this would be Base, but defining it so breaks the build
final Base data;
Map toJson() => _$DataToJson(this);
}
```
Changing `final Base data` to `final Base data` results in this error:
```
[SEVERE] json_serializable on lib/src/data.dart:
Could not generate `fromJson` code for `data`.
To support the type `Base` 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:json_serializable_test/src/data.dart:30:17
╷
[line number] │ final Base data;
```
This despite the fact that a `JsonConverter` is clearly being used.
For posterity, I originally reported this at rrousselGit/freezed#1074, and was (correctly, it seems) directed here.
Contributor guide
Assessment
This issue has not been assessed yet.