Sub topic 3
Serializing enums
This chapter assumes you have worked through the earlier chapters: you can write Dart classes with null safety, you have added json_annotation, json_serializable, and build_runner to a Flutter project, and you can run dart run build_runner build.
Serializing enums
By default, json_serializable writes an enum as its value name, such as "pending". Add @JsonValue to an enum value when the API uses a different string.
import 'package:json_annotation/json_annotation.dart';
part 'order_status.g.dart';
@JsonEnum()
enum OrderStatus {
pending,
@JsonValue('cancelled_by_user')
cancelled,
}A non-nullable enum field throws an ArgumentError when the input holds an unknown value. A nullable enum field returns null instead.
Writing a JsonConverter
A JsonConverter is a class that tells the generator how to convert one Dart type to a JSON type and back. Use one when a type, such as DateTime stored as milliseconds, is not handled by default.
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;
}Place @EpochMillisConverter() above the field it applies to.
Handling malformed JSON and checked mode
Set checked: true in @JsonSerializable to make the generated code report the failing key. It then throws a CheckedFromJsonException that names the field.
User? tryParseUser(Map<String, dynamic> json) {
try {
return User.fromJson(json);
} on CheckedFromJsonException catch (e) {
print('Field ${e.key} failed: ${e.message}');
return null;
}
}Testing models with round trips
A round-trip test encodes a model to JSON, decodes it again, and checks that each field matches the original. This catches missing keys, wrong types, and converter mistakes in one test.
Generic response wrappers
For a wrapper such as ApiResponse<T>, set genericArgumentFactories: true on the class. The generated fromJson then takes a function that converts the inner data field.
Parsing large payloads with compute
Parsing a large response on the main isolate can freeze the UI. Pass a top-level parsing function to compute, which runs it in a background isolate.
import 'package:flutter/foundation.dart';
final users = await compute(parseUsers, responseBody);The parsing function must be top-level or static, not a closure.
Related tools and when to choose them
| Tool | Choose it when |
|---|---|
| json_serializable | You want generated `fromJson` and `toJson` with few dependencies. |
| freezed | You need immutable classes, `copyWith`, and union types, with JSON support. |
| dart_mappable | You want generated mapping code between models and JSON. |
Exercise
A field status holds the value "archived", which is not in OrderStatus. The field is declared as OrderStatus status (non-nullable). What happens when Order.fromJson runs, and how would you change the field to return null instead?
Show answer
The generated code throws an ArgumentError. Declare the field as OrderStatus? status so the generated code returns null for unknown values.