Sub topic 10
Writing a JsonConverter
Assume you know Dart classes, null safety, annotations, and the basic json_serializable workflow. This chapter focuses on fields whose JSON representation does not match the Dart type directly.
Why use a converter?
json_serializable handles common types such as String, int, List, nested models, and ordinary DateTime values. Some APIs use a different representation. For example, an API might store a date as milliseconds since the Unix epoch:
{
"updated_at": 1710000000000
}Your Dart model can still expose this value as a DateTime. A JsonConverter is a class that defines both directions of this conversion:
| Direction | Input | Output |
|---|---|---|
| `fromJson` | JSON value, such as `int` | Dart value, such as `DateTime` |
| `toJson` | Dart value, such as `DateTime` | JSON value, such as `int` |
The converter must describe both types with JsonConverter<DartType, JsonType>.
Build an epoch converter
Create a converter for UTC epoch milliseconds:
import 'package:json_annotation/json_annotation.dart';
class EpochMillisConverter implements JsonConverter<DateTime, int> {
const EpochMillisConverter();
@override
DateTime fromJson(int json) {
return DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);
}
@override
int toJson(DateTime object) {
return object.millisecondsSinceEpoch;
}
}fromJson runs while generated code creates a model. It turns the integer into a UTC DateTime. toJson runs while generated code creates a map. It turns the DateTime back into milliseconds.
The converter is declared const so it can be used as a constant annotation.
Apply the converter to a field
Attach the converter to the field that uses the special representation:
import 'package:json_annotation/json_annotation.dart';
part 'session.g.dart';
@JsonSerializable()
class Session {
const Session({
required this.id,
required this.updatedAt,
});
factory Session.fromJson(Map<String, dynamic> json) =>
_$SessionFromJson(json);
final String id;
@EpochMillisConverter()
final DateTime updatedAt;
Map<String, dynamic> toJson() => _$SessionToJson(this);
}Run the generator after adding the model and converter:
dart run build_runner build --delete-conflicting-outputsThe generated session.g.dart file calls EpochMillisConverter for updatedAt. You should not edit that generated file manually.
Handle nullability and validation
A converter for DateTime and int does not automatically accept null. For a nullable field, use a nullable converter type and decide how null should behave:
class NullableEpochMillisConverter
implements JsonConverter<DateTime?, int?> {
const NullableEpochMillisConverter();
@override
DateTime? fromJson(int? json) {
if (json == null) return null;
return DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);
}
@override
int? toJson(DateTime? object) {
return object?.millisecondsSinceEpoch;
}
}A converter should also validate values when the API can send invalid data. For example, reject a timestamp outside the range your application supports by throwing a clear exception. Generated checked decoding can then add field and key context to the error.
> callout note > Keep the converter focused on representation. Authentication, network requests, and business rules belong outside the converter.
Check the round trip
A round-trip test serializes a model and reads the resulting map back:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('epoch time survives a JSON round trip', () {
final session = Session(
id: 's-1',
updatedAt: DateTime.fromMillisecondsSinceEpoch(
1710000000000,
isUtc: true,
),
);
final restored = Session.fromJson(session.toJson());
expect(restored.id, session.id);
expect(restored.updatedAt, session.updatedAt);
});
}Exercise
An API returns price as a string such as "19.95", but your Dart model needs a double. What should the converter's type parameters be?
Show answer
Use JsonConverter<double, String>, then parse the string in fromJson and convert the double to a string in toJson.