rrousselGit / freezed

Code generation for immutable classes that has a simple syntax/API without compromising on the features.
https://pub.dev/packages/freezed
1.92k stars 236 forks source link

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

Open MattiaPispisa opened 3 days ago

MattiaPispisa commented 3 days ago

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 commented 3 days ago

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