Sub topic 9
Serializing enums
This chapter covers how jsonserializable converts Dart enums to and from JSON. It assumes you can write a Dart class with null safety, you have `jsonannotation, jsonserializable, and buildrunner set up, and you have already generated a .g.dart` file for an annotated model. If you have not, go back to the setup and code generation chapters first.
What the generator does with an enum by default
JSON has no enum type. A server sends a string or a number, and your Dart code wants a value of a specific enum. json_serializable bridges the two. By default it uses the enum value's identifier, such as pending, as the JSON string.
Take this model:
import 'package:json_annotation/json_annotation.dart';
part 'ticket.g.dart';
enum Priority { low, medium, high }
@JsonSerializable()
class Ticket {
const Ticket({required this.title, required this.priority});
factory Ticket.fromJson(Map<String, dynamic> json) => _$TicketFromJson(json);
final String title;
final Priority priority;
Map<String, dynamic> toJson() => _$TicketToJson(this);
}Calling Ticket(title: 'Fix login', priority: Priority.high).toJson() returns {title: Fix login, priority: high}. Reading {"title": "Fix login", "priority": "high"} gives back Priority.high.
The generated code uses a lookup map. It is built from the enum's values and is emitted into ticket.g.dart as a private map named _$PriorityEnumMap. You do not write it. The generator creates it the first time it sees an enum used by an annotated class.
Two points follow from this:
- The enum must be visible to the generator. It can be declared in the same file or imported.
- The default names are the Dart identifiers. If you rename
hightourgentin Dart, the JSON changes too, and old data no longer parses.
That second point is the main reason to control the names explicitly.
Controlling the JSON value with @JsonValue
Dart enum identifiers must follow Dart naming rules. Servers do not. An API might send "in-progress", "CANCELLED_BY_USER", or the number 2. Annotate each enum value with @JsonValue to say what the JSON representation is.
import 'package:json_annotation/json_annotation.dart';
part 'task.g.dart';
enum TaskState {
@JsonValue('todo')
todo,
@JsonValue('in-progress')
inProgress,
@JsonValue('done')
done,
}
@JsonSerializable()
class Task {
const Task({required this.name, required this.state});
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
final String name;
final TaskState state;
Map<String, dynamic> toJson() => _$TaskToJson(this);
}Now TaskState.inProgress serializes as "in-progress", and "in-progress" parses back to TaskState.inProgress. The Dart name and the wire name are decoupled, so you can rename the Dart identifier later without breaking the contract.
@JsonValue accepts a String or an int. All annotated values in one enum must use the same type. Mixing strings and integers in one enum is a build error.
Numeric enums
Some APIs send integers. Use int values in @JsonValue:
import 'package:json_annotation/json_annotation.dart';
enum Level {
@JsonValue(0)
debug,
@JsonValue(1)
info,
@JsonValue(2)
error,
}A model with a Level field then writes and reads 0, 1, and 2. Numeric values are compact but hard to read in logs, so prefer strings unless the server forces integers on you.
Renaming every value at once with @JsonEnum
Adding @JsonValue to each constant is repetitive when the whole enum follows one convention. Put @JsonEnum on the enum itself and set fieldRename:
import 'package:json_annotation/json_annotation.dart';
@JsonEnum(fieldRename: FieldRename.snake)
enum PaymentMethod {
creditCard,
bankTransfer,
cashOnDelivery,
}The JSON values become credit_card, bank_transfer, and cash_on_delivery. The available strategies are the same as for classes: none, kebab, snake, pascal, camel, and screamingSnake. An explicit @JsonValue on a single constant still wins over the enum-wide rule, so you can handle one odd value without abandoning the convention.
The class-level fieldRename on @JsonSerializable renames field keys, not enum values. The two settings are independent. A class with fieldRename: FieldRename.snake does not change how its enum fields are spelled.
When you need @JsonEnum explicitly
Normally the generator discovers enums by seeing them used as field types. An enum that is never used directly as a field type does not get a helper. A common case is an enum used only as a map key, or one you plan to encode with the public helper functions. Marking the enum with @JsonEnum(alwaysCreate: true) makes the generator emit a public lookup map named _$PaymentMethodEnumMap in the part file, which you can use for your own conversions.
Unknown values: the most common enum failure
A server adds a new status. Your released app does not know it. What happens?
By default, the generated fromJson throws an ArgumentError when the string matches no enum value. In the app, that is an uncaught exception somewhere in your parsing code, and the whole screen can fail because one field was new.
There are two ways to handle it, and the choice depends on whether an unknown value should be fatal.
Option 1: a fallback with unknownEnumValue
Set unknownEnumValue in @JsonKey to the value used when nothing matches:
import 'package:json_annotation/json_annotation.dart';
part 'shipment.g.dart';
enum ShipmentStatus {
pending,
shipped,
delivered,
@JsonValue('unknown')
unknown,
}
@JsonSerializable()
class Shipment {
const Shipment({required this.id, required this.status});
factory Shipment.fromJson(Map<String, dynamic> json) =>
_$ShipmentFromJson(json);
final String id;
@JsonKey(unknownEnumValue: ShipmentStatus.unknown)
final ShipmentStatus status;
Map<String, dynamic> toJson() => _$ShipmentToJson(this);
}If the server sends "status": "lost_in_transit", the field becomes ShipmentStatus.unknown. The model parses and the UI can show a neutral label.
Keep two details in mind:
unknownEnumValueapplies to the specific field. You repeat it on every field of that enum type.- A fallback value only helps if it is a real member of the enum. Add an explicit
unknownconstant for this purpose.
Option 2: a nullable field
If the enum field is nullable, an unmatched value does not produce a fallback by default. The generator still throws for a non-null string it cannot match. Combine the nullable type with unknownEnumValue: JsonKey.nullForUndefinedEnumValue to receive null instead:
@JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue)
final ShipmentStatus? status;This is useful when "unknown" is not a state your app models and you prefer to treat the value as missing.
What a missing key does
An absent key and an unknown value are different failures. If the key is missing and the field is non-nullable and required, the generated code throws a cast error. If the field is nullable, a missing key gives null. A defaultValue in @JsonKey covers the missing-key case, not the unknown-value case. Use unknownEnumValue for the second.
Enhanced enums with a custom value field
Dart's enhanced enums can carry fields. When the wire value lives in a field, @JsonEnum(valueField: ...) tells the generator to read it:
import 'package:json_annotation/json_annotation.dart';
@JsonEnum(valueField: 'code')
enum Currency {
usd('USD'),
eur('EUR'),
jpy('JPY');
const Currency(this.code);
final String code;
}Currency.eur serializes as "EUR". The named field must be a final instance field of type String or int, and it is read from the constructor argument. This keeps the wire value next to the constant it describes and avoids a separate annotation per value.
Choosing an approach
| Situation | Use |
|---|---|
| Wire names match Dart identifiers | Nothing; defaults work |
| One or two odd names | `@JsonValue` on those constants |
| A whole naming convention differs | `@JsonEnum(fieldRename: ...)` |
| Value lives in an enum field | `@JsonEnum(valueField: ...)` |
| Server may add new values | `unknownEnumValue` on the field |
| Integer wire values | `@JsonValue(int)` on each constant |
Enums inside collections
Lists and maps of enums use the same lookup. A List<Priority> serializes as a list of strings, and each element is matched individually. An unknown element in a list throws for the whole list unless you handle it. The unknownEnumValue option works on a list field too, replacing unknown elements with the fallback value.
Map keys also work. A Map<Priority, int> produces JSON object keys as the enum's wire strings. Use string wire values for key enums, because JSON object keys are always strings.
Round-trip testing for enums
Every enum value should survive a trip through JSON. Looping over values catches typos in @JsonValue and missed constants:
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('every TaskState survives a round trip', () {
for (final state in TaskState.values) {
final task = Task(name: 'x', state: state);
final json = jsonDecode(jsonEncode(task.toJson())) as Map<String, dynamic>;
expect(Task.fromJson(json).state, state);
}
});
test('an unknown status falls back to unknown', () {
final shipment = Shipment.fromJson({'id': 's1', 'status': 'lost_in_transit'});
expect(shipment.status, ShipmentStatus.unknown);
});
}Because the loop uses values, adding a new constant later is covered without editing the test.
How enum handling flows
The diagram shows the decision the generated fromJson makes for an enum field.
Common mistakes
- Renaming a Dart enum constant without a
@JsonValue, which silently changes the JSON. - Forgetting to rerun
dart run build_runner build --delete-conflicting-outputsafter editing enum annotations. The.g.dartfile keeps the old map. - Assuming
fieldRenameon the class changes enum values. It does not. - Using
unknownEnumValueon one field and expecting it to cover other fields with the same enum type. - Mixing
Stringandintvalues within one enum.
Exercise
An API sends order states as "new", "in-transit", and "done". You write enum OrderState { newOrder, inTransit, done } with no annotations. What happens when parsing "new" and "in-transit", and how do you fix it?
Show answer
Parsing fails with an ArgumentError for both, because the default wire values are the Dart identifiers "newOrder" and "inTransit". "done" works. Fix it by adding @JsonValue('new') to newOrder and @JsonValue('in-transit') to inTransit, then rerun build_runner. Alternatively, rename the constants to match, though @JsonValue keeps the Dart names free to change.
Exercise
A field is declared final Status status; and the server starts sending a value your enum lacks. Name two ways to stop parsing from throwing and say how each changes the field's type or value.
Show answer
First, add an unknown constant to the enum and put @JsonKey(unknownEnumValue: Status.unknown) on the field. The type stays non-null and the field holds Status.unknown. Second, make the field nullable (Status?) and use @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue). The field holds null for unknown values.