json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

[Feature Request] Generate `fromJson`, `toJson` from typedef of `Records` types

Open definev opened this issue 1 year ago • 4 comments

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);
}

definev avatar Jun 05 '23 10:06 definev

I think supporting extension types on records prop may be appropriate.

BoyleSeo avatar Jul 27 '23 08:07 BoyleSeo

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

BoyleSeo avatar Feb 16 '24 06:02 BoyleSeo

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.

ralph-bergmann avatar May 10 '24 23:05 ralph-bergmann