temporal_json_converter
json_serializable converters for every type in the temporal package.
Getting started
dependencies:
temporal: ^0.1.1
temporal_json_converter: ^0.1.0
json_annotation: ^4.9.0
dev_dependencies:
build_runner: ^2.0.0
json_serializable: ^6.0.0
Usage
Annotate fields with the static converter that matches the type:
import 'package:json_annotation/json_annotation.dart';
import 'package:temporal/temporal.dart';
import 'package:temporal_json_converter/temporal_json_converter.dart';
part 'event.g.dart';
@JsonSerializable()
class Event {
@TemporalJsonConverter.plainDate
final PlainDate date;
@TemporalJsonConverter.plainTime
final PlainTime time;
@TemporalJsonConverter.zonedDateTime
final ZonedDateTime start;
@TemporalJsonConverter.instant
final Instant createdAt;
@TemporalJsonConverter.duration
final TemporalDuration length;
const Event({
required this.date,
required this.time,
required this.start,
required this.createdAt,
required this.length,
});
factory Event.fromJson(Map<String, dynamic> json) => _$EventFromJson(json);
Map<String, dynamic> toJson() => _$EventToJson(this);
}
All converters serialize to and from ISO 8601 strings — the canonical wire format for each type:
| Converter | Dart type | Example JSON value |
|---|---|---|
TemporalJsonConverter.plainDate |
PlainDate |
"2024-03-15" |
TemporalJsonConverter.plainTime |
PlainTime |
"14:30:00" |
TemporalJsonConverter.plainDateTime |
PlainDateTime |
"2024-03-15T14:30:00" |
TemporalJsonConverter.zonedDateTime |
ZonedDateTime |
"2024-03-15T14:30:00[America/New_York]" |
TemporalJsonConverter.instant |
Instant |
"2024-03-15T19:30:00Z" |
TemporalJsonConverter.duration |
TemporalDuration |
"P1Y2M3DT4H" |
TemporalJsonConverter.plainYearMonth |
PlainYearMonth |
"2024-03" |
TemporalJsonConverter.plainMonthDay |
PlainMonthDay |
"--03-15" |
The converters can also be used directly without json_serializable:
const converter = TemporalJsonConverter.plainDate;
final date = converter.fromJson('2024-03-15'); // PlainDate
final json = converter.toJson(date); // '2024-03-15'
Additional information
- temporal — the Temporal types package
- TC39 Temporal proposal
- File issues at the GitHub issue tracker