Sub topic 10
Writing a JsonConverter
This chapter assumes you can annotate a model with @JsonSerializable(), run build_runner, and read the generated .g.dart file. It also assumes you know Dart generics and const constructors.
json_serializable handles String, int, double, bool, num, DateTime, Uri, BigInt, enums, and nested annotated classes. It can't serialize a type it has never seen, such as a Money class. It also can't serialize a known type in a format other than its default. A JsonConverter is a small class that tells the generator how to translate one Dart type to and from one JSON type.
What a converter is
JsonConverter<S, T> is an abstract class from json_annotation with two type parameters:
Sis the Dart type in your model, such asDateTime.Tis the type that appears in the JSON, such asintorString.
You implement two methods. fromJson(T json) returns an S. toJson(S object) returns a T.
import 'package:json_annotation/json_annotation.dart';
class EpochMillisConverter implements JsonConverter<DateTime, int> {
const EpochMillisConverter();
@override
DateTime fromJson(int json) =>
DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);
@override
int toJson(DateTime object) => object.millisecondsSinceEpoch;
}The constructor must be const. Dart only allows annotations built from constant expressions, and a converter is used as an annotation.
Applying a converter to a field
Put the converter annotation directly above the field. Declaring the class and running the generator shows how it is used.
import 'package:json_annotation/json_annotation.dart';
part 'event.g.dart';
class EpochMillisConverter implements JsonConverter<DateTime, int> {
const EpochMillisConverter();
@override
DateTime fromJson(int json) =>
DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);
@override
int toJson(DateTime object) => object.millisecondsSinceEpoch;
}
@JsonSerializable()
class Event {
const Event({
required this.title,
required this.updatedAt,
this.deletedAt,
});
factory Event.fromJson(Map<String, dynamic> json) => _$EventFromJson(json);
final String title;
@EpochMillisConverter()
final DateTime updatedAt;
@EpochMillisConverter()
final DateTime? deletedAt;
Map<String, dynamic> toJson() => _$EventToJson(this);
}After dart run build_runner build --delete-conflicting-outputs, event.g.dart calls const EpochMillisConverter().fromJson(...) for updatedAt and .toJson(...) when writing it. Without the annotation, the generator would expect an ISO 8601 string and fail on the integer.
Look at deletedAt. The converter is declared for a non-nullable DateTime, yet it is also applied to a DateTime? field. The generator adds a null check around the converter call. A missing or null value becomes null without reaching your code, so your converter only handles real values.
Three places to apply a converter
| Where | Syntax | Scope |
|---|---|---|
| On a field | `@EpochMillisConverter()` above the field | That one field |
| On a class | `@EpochMillisConverter()` above the class declaration | Every field in that class whose type is `S` |
| In class options | `@JsonSerializable(converters: [EpochMillisConverter()])` | Every field in that class whose type is `S` |
Use the class-level forms when a model has several timestamps in the same format. A field-level converter always wins over a class-level one, so you can set a default and override single fields.
A converter does not follow your model around. If Order contains a List<Event>, each Event uses its own annotations, and Order needs its own converter setup for any DateTime fields it declares.
Converting to a structured value
The JSON type T does not have to be a primitive. A converter can map a custom class to a string, a number, a Map<String, dynamic>, or a list. This example stores money as a decimal string such as "12.50", which avoids floating point rounding by keeping the Dart side in whole cents.
import 'package:json_annotation/json_annotation.dart';
part 'invoice.g.dart';
class Money {
const Money(this.cents);
final int cents;
@override
bool operator ==(Object other) => other is Money && other.cents == cents;
@override
int get hashCode => cents.hashCode;
}
class MoneyConverter implements JsonConverter<Money, String> {
const MoneyConverter();
static final _pattern = RegExp(r'^(\d+)\.(\d{2})$');
@override
Money fromJson(String json) {
final match = _pattern.firstMatch(json);
if (match == null) {
throw FormatException('Expected a value like "12.50"', json);
}
return Money(int.parse(match[1]!) * 100 + int.parse(match[2]!));
}
@override
String toJson(Money object) {
final whole = object.cents ~/ 100;
final fraction = (object.cents % 100).toString().padLeft(2, '0');
return '$whole.$fraction';
}
}
@JsonSerializable()
@MoneyConverter()
class Invoice {
const Invoice({required this.number, required this.total, required this.tax});
factory Invoice.fromJson(Map<String, dynamic> json) =>
_$InvoiceFromJson(json);
final String number;
final Money total;
final Money tax;
Map<String, dynamic> toJson() => _$InvoiceToJson(this);
}The annotation sits on the class, so both total and tax use MoneyConverter. This version only accepts non-negative amounts with exactly two decimals. If your API sends other shapes, extend the pattern before shipping.
Note that Money needs no annotations of its own. The converter is the only place that knows how it looks in JSON.
Choosing between a converter and @JsonKey functions
For a one-off conversion on a single field, @JsonKey accepts function references. This avoids writing a whole class.
import 'package:json_annotation/json_annotation.dart';
part 'ping.g.dart';
DateTime _secondsToDate(int seconds) =>
DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true);
int _dateToSeconds(DateTime date) => date.millisecondsSinceEpoch ~/ 1000;
@JsonSerializable()
class Ping {
const Ping({required this.sentAt});
factory Ping.fromJson(Map<String, dynamic> json) => _$PingFromJson(json);
@JsonKey(fromJson: _secondsToDate, toJson: _dateToSeconds)
final DateTime sentAt;
Map<String, dynamic> toJson() => _$PingToJson(this);
}The functions must be top-level or static. Use this when the logic belongs to one field. Use a JsonConverter when the same rule applies to several fields or several classes, or when you want to test the rule on its own.
Edge cases and common errors
- Type mismatch before your code runs. If the converter's
Tisintand the server sends"1700000000000"as a string, the generated code throws aTypeErrorwhen it casts the value. YourfromJsonnever sees it. If a server is inconsistent, declareTasObjectordynamicand branch insidefromJson. - Converter not applied. The generator matches on the exact type
S. AJsonConverter<DateTime, int>does not apply to a field of typeDateTime?through a class-level annotation unless the nullable handling described above covers it. If a field still fails with an "unsupported type" error, annotate it directly. - Local versus UTC.
DateTime.fromMillisecondsSinceEpochreturns a local time unless you passisUtc: true. A round trip is lossless either way, because the millisecond value is the same. Comparing against a UTCDateTimein tests is not equal to a local one, though. Pick one and stay consistent. - Stale generated code. Adding or removing a converter annotation changes the generated file. Re-run
build_runner, or keepdart run build_runner watchopen. - Throwing from a converter. Throw a
FormatExceptionwith a clear message for bad input. Chapter 11 covers how checked mode wraps such errors so the failing field is named.
Testing a converter
Test the converter by itself, then confirm a model round trip. The standalone test is quick and pinpoints the failing rule.
import 'package:flutter_test/flutter_test.dart';
void main() {
const converter = MoneyConverter();
test('MoneyConverter round trips', () {
expect(converter.toJson(converter.fromJson('12.50')), '12.50');
expect(converter.fromJson('0.05'), const Money(5));
});
test('MoneyConverter rejects malformed text', () {
expect(() => converter.fromJson('12.5'), throwsFormatException);
expect(() => converter.fromJson('abc'), throwsFormatException);
});
}Import the file that declares Money and MoneyConverter at the top of your test file. The first test proves that toJson and fromJson are inverses. The second proves that bad input fails loudly instead of producing wrong money.
Summary of the working model
- Choose
S(your Dart type) andT(what the JSON contains). - Implement
JsonConverter<S, T>with aconstconstructor. - Annotate a field, a class, or list it in
converters. - Re-run
build_runner. - Test the converter alone, and make sure invalid input throws.
Exercise
A model has final DateTime createdAt; and final DateTime? archivedAt;. The API sends both as integer seconds since the epoch, and archivedAt is sometimes null. Write the converter, say where you would annotate it so both fields use it, and explain what happens to a null archivedAt.
Show answer
Write class EpochSecondsConverter implements JsonConverter<DateTime, int> with a const constructor. fromJson(int json) returns DateTime.fromMillisecondsSinceEpoch(json * 1000, isUtc: true). toJson(DateTime object) returns object.millisecondsSinceEpoch ~/ 1000. Annotate the class with @EpochSecondsConverter() above @JsonSerializable(), or pass converters: [EpochSecondsConverter()], so both fields use it. A null archivedAt is handled by a null check in the generated code, so the converter is never called and the field becomes null. Re-run build_runner after adding the annotation.
Exercise
When would you choose @JsonKey(fromJson: ..., toJson: ...) over a JsonConverter, and what restriction applies to the functions you pass?
Show answer
Choose @JsonKey functions for a conversion that applies to a single field and is unlikely to be reused. Choose a JsonConverter when several fields or classes share the rule, or when you want to unit test it as its own class. The functions passed to @JsonKey must be top-level or static, because annotation arguments have to be compile-time constants.