google / google/json_serializable.dart

Parameterized JsonConverter

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

Description

I would like to request that JsonConverter classes support parameter.

Given this Example:

```dart
class UserProfile {

@DateTimeLocalJsonConverter()
final DateTime? birthdate;

const UserProfile(this.birthdate);
}
```

```dart
class DateTimeUtcJsonConverter extends JsonConverter {
/// if true, utc to local conversion is disabled
final bool disableFromUtc;

/// if true, local to utc conversion is disabled
final bool disableToUtc;

const DateTimeUtcJsonConverter({this.disableFromUtc = false, this.disableToUtc = false});

@override
DateTime fromJson(String json) {
if (disableFromUtc) return DateTime.parse(json);

return DateTime.parse(json).toLocal();
}

@override
String toJson(DateTime object) {
if (disableToUtc) return object.toIso8601String();

return object.toUtc().toIso8601String();
}
}

```

As we see in the example, it was a bad idea to convert the birthday of a user into a utc date.
If the code generator would support parameter in JsonConverter, this would be helpful in reversing this mistake.

The alternative for parameter are currently writing a complete converter with the correct conversion or using a typedef.
```dart
const localDateTimeConverter = DateTimeUtcJsonConverter(disableToUtc: true);
```

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.