google / google/json_serializable.dart

[Suggestion] Add a project wide option and a @JsonKey option to customize how far to parse DateTime

Open
#1,315 9 comments 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

## Why

Sometimes one wants to parse dart's `DateTime` object only to Date instead of microseconds, but json_serializable does not have an option to specify this. This applies on both toJson and fromJson.

At the same time, how far one wants to parse `DateTime` may vary on every usecase.

## Suggestion

- Add a project wide option to specify how far to be parsed such as below in build.yaml or pubspec.yaml:
```yaml
targets:
$default:
builders:
json_serializable:
options:
date_time_parse: "toSeconds" # or "toDays" or "toHours" etc.
```
- Add an option to set on each field member as such:
```dart
@JsonSerializable()
class User {
User(this.name, this.email);

String name;
String email;
@JsonKey(dateTimeToParse: "toSeconds") DateTime date;

Map toJson() => _$UserToJson(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.