Reputation: 629
How can I set a converter globally to replace the buildin datetime for example?
this does not appear in the documentation
https://pub.dev/packages/json_serializable
replace the datetime converter with a custom one globally for all classes
Upvotes: 1
Views: 812
Reputation: 17616
First, create your converter:
class DateTimestampConverter implements JsonConverter<DateTime?, Timestamp?> {
const DateTimestampConverter();
@override
DateTime? fromJson(Timestamp? timestamp) => timestamp?.toDate();
@override
Timestamp? toJson(DateTime? dateTime) => dateTime != null ? Timestamp.fromDate(dateTime) : null;
}
Then add it to your @JsonSerializable annotation:
@JsonSerializable(
explicitToJson: true,
converters: [DateTimestampConverter()],
)
Upvotes: 0