google / google/json_serializable.dart

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

Open
#1,327 4 comments 17 reactions 0 assignees View on GitHub
Type: enhancement
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

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

typedef RoomPlanBookingInfo = ({
/// Id of room plan
RoomPlanEntity roomPlan,

/// Properties
List 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 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
```dart
@JsonSerializable()
typedef RoomPlanBookingInfo = ({
/// Id of room plan
RoomPlanEntity roomPlan,

/// Properties
List 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
```dart
extension RoomPlanBookingInfoCodable on RoomPlanBookingInfo {
static RoomPlanBookingInfo fromJson(Map json) => _$RoomPlanBookingInfoFromJson(json);

Map toJson() => _$RoomPlanBookingInfoToJson(this);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.