google / google/json_serializable.dart
Use of a generic JsonConverter
- Dominant language
- Dart
- Stars
- 1.6k
- Forks
- 461
- Avg merge
- 45m
- Merged PRs (30d)
- 1
Description
Hello,
I'm stuck on a use case, and am looking for help. I'm using a graphql api that I don't want to modify (directus) and in some cases, the list of elements (here posts) is nested in a sub-element (here "post_id", see fromJson in the WrappedConverter2).
```dart
@freezed
class ExamSessionFullDto with _$ExamSessionFullDto implements IExamSessionFull {
const ExamSessionFullDto._();
const factory ExamSessionFullDto({
@StringToIntConverter() required int id,
required String title,
@WrappedConverter2() List? posts,
}) = _ExamSessionFullDto;
factory ExamSessionFullDto.fromJson(Map json) =>
_$ExamSessionFullDtoFromJson(json);
}
class WrappedConverter2 extends JsonConverter> {
const WrappedConverter2();
@override
PostDto fromJson(Map json) {
return PostDto.fromJson(json["post_id"]);
}
@override
Map toJson(PostDto object) {
return object.toJson();
}
}
```
This code works, but I have to have a converter every time I have a list of items, which isn't ideal because I have to do a lot of copy-and-paste code, which is bad practice.
I've made several attempts to make my converter generic, but unfortunately when I use genericity it doesn't work with freezed, or it's probably me who can't get it right.
Does anyone have a good way to have a single JsonConverter or some other solution that I can apply to all my objects that have sublists of this type?
The idea would be to have something like
```dart
class ManyToManyRelationshipConverter
extends JsonConverter> {
final String jsonKey;
final KreaticItemsConverter converter;
const ManyToManyRelationshipConverter.forPost(
{this.jsonKey = "post_id", this.converter = const PostDtoConverter() as KreaticItemsConverter});
@override
E fromJson(Map json) {
return converter.fromJson(json[jsonKey]);
}
@override
Map toJson(E object) {
return converter.toJson(object);
}
}
```
Contributor guide
Assessment
This issue has not been assessed yet.