Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of a generic JsonConverter #1398

Open
alexdess opened this issue Feb 15, 2024 · 0 comments
Open

Use of a generic JsonConverter #1398

alexdess opened this issue Feb 15, 2024 · 0 comments

Comments

@alexdess
Copy link

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).

@freezed
class ExamSessionFullDto with _$ExamSessionFullDto implements IExamSessionFull {
  const ExamSessionFullDto._(); 

  const factory ExamSessionFullDto({
    @StringToIntConverter() required int id,
    required String title,
    @WrappedConverter2() List<PostDto>? posts,
  }) = _ExamSessionFullDto;

  factory ExamSessionFullDto.fromJson(Map<String, dynamic> json) =>
      _$ExamSessionFullDtoFromJson(json);
}

class WrappedConverter2 extends JsonConverter<PostDto, Map<String, dynamic>> {
  const WrappedConverter2();
  @override
  PostDto fromJson(Map<String, dynamic> json) {
    return PostDto.fromJson(json["post_id"]);
  }

  @override
  Map<String, dynamic> 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

class ManyToManyRelationshipConverter<E>
    extends JsonConverter<E, Map<String, dynamic>> {
  final String jsonKey;
  final KreaticItemsConverter<E> converter;

  const ManyToManyRelationshipConverter.forPost(
      {this.jsonKey = "post_id", this.converter = const PostDtoConverter() as KreaticItemsConverter<E>});

  @override
  E fromJson(Map<String, dynamic> json) {
    return converter.fromJson(json[jsonKey]);
  }

  @override
  Map<String, dynamic> toJson(E object) {
    return converter.toJson(object);
  }
}
@alexdess alexdess changed the title Utilisation d'un JsonConverter generic Use of a generic JsonConverter Feb 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant