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