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

Dynamically specify a different JSON key for the generic field #1129

Open
MattiaPispisa opened this issue Oct 1, 2024 · 1 comment
Open
Assignees
Labels
enhancement New feature or request

Comments

@MattiaPispisa
Copy link

Currently, freezed allows deserializing/serializing typed objects using generics. However, in certain cases, it may be useful to specify a different JSON key dynamically for the generic field, depending on how it’s being used.

Example

@Freezed(genericArgumentFactories: true)
class BodyContainer<T> with _$BodyContainer<T> {
  const factory BodyContainer({
    required String cmd,
    required T customData,
  }) = _BodyContainer;

  factory BodyContainer.fromJson(
    Map<String, dynamic> json,
    T Function(Object?) fromJsonT,
  ) =>
      _$BodyContainerFromJson(json, fromJsonT);
}

Proposal

The proposal is to extend the fromJson method by adding an extra parameter, jsonKey, which would allow specifying the JSON field that contains the generic data at the time of deserialization/serializations:

Example

@Freezed(genericArgumentFactories: true)
class BodyContainer<T> with _$BodyContainer<T> {
  const factory BodyContainer({
    required String cmd,
    required T customData,
  }) = _BodyContainer;

  factory BodyContainer.fromJson(
    Map<String, dynamic> json,
    T Function(Object?) fromJsonT,
    String jsonKey
  ) =>
      _$BodyContainerFromJson(json, fromJsonT, jsonKey);
}

Motivation

In an API context, it’s common to have recurring response or request body structures where some fields are specific while others are common. By adding the ability to specify the JSON key at deserialization time, the code becomes more flexible and capable of handling these variations without duplicating serialization/deserialization logic.

If the idea is considered valid, I can work on developing the system and submit a pull request to integrate this functionality.

@rrousselGit
Copy link
Owner

Reasonable, but a bit difficult. I probably won't implement thar before a while

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants
@rrousselGit @MattiaPispisa and others