json_serializable.dart
json_serializable.dart copied to clipboard
[Feature Request] Generate `fromJson`, `toJson` from typedef of `Records` types
Since Dart 3.0, we have Records and it similar to define a class contains only data so in my view this code is equalvalent.
typedef RoomPlanBookingInfo = ({
/// Id of room plan
RoomPlanEntity roomPlan,
/// Properties
List<ServiceBookingInfo> services,
int numberOfAdults,
int numberOfChildren,
int numberOfBaby,
String? note,
({
String firstName,
String lastName,
String email,
String phoneNumber,
}) guest,
});
@JsonSerializable()
class RoomPlanBookingInfoClass {
final RoomPlanEntity roomPlan;
final List<ServiceBookingInfo> services;
final int numberOfAdults;
final int numberOfChildren;
final int numberOfBaby;
final String? note;
final ({
String firstName,
String lastName,
String email,
String phoneNumber,
}) guest;
RoomPlanBookingInfoClass({
required this.roomPlan,
required this.services,
required this.numberOfAdults,
required this.numberOfChildren,
required this.numberOfBaby,
required this.note,
required this.guest,
});
}
If we support typedef for Records
typedef the code is elegant like this
@JsonSerializable()
typedef RoomPlanBookingInfo = ({
/// Id of room plan
RoomPlanEntity roomPlan,
/// Properties
List<ServiceBookingInfo> services,
int numberOfAdults,
int numberOfChildren,
int numberOfBaby,
String? note,
({
String firstName,
String lastName,
String email,
String phoneNumber,
}) guest,
});
The fromJson
/ toJson
methods are implemented in RoomPlanBookingInfoCodable
from generator sth like
extension RoomPlanBookingInfoCodable on RoomPlanBookingInfo {
static RoomPlanBookingInfo fromJson(Map<String, dynamic> json) => _$RoomPlanBookingInfoFromJson(json);
Map<String, dynamic> toJson() => _$RoomPlanBookingInfoToJson(this);
}
I think supporting extension types on records prop may be appropriate.
I think supporting extension types on records prop may be appropriate.
I just realized it's not simple to do. convert::jsonEncode function cannot invoke toJson method anyway because extension types are 0 cost wrapper and do not provide v-table to Object reference..
I'm wondering if it might be a compromise to implement only fromJson
for records instead of not supporting records at all. Most of the time, I only need fromJson
.