Sub topic 9
Serializing enums
This chapter assumes you know Dart classes, null safety, maps, and basic json_serializable models. You will use generated code rather than writing fromJson and toJson by hand.
An enum is a type with a fixed set of named values. For example, an order can be pending, shipped, or cancelled. JSON has no enum type, so json_serializable converts each enum value to a JSON string.
Default enum names
By default, the JSON value matches the Dart enum value:
| Dart value | JSON value |
|---|---|
| `OrderStatus.pending` | `"pending"` |
| `OrderStatus.shipped` | `"shipped"` |
| `OrderStatus.cancelled` | `"cancelled"` |
import 'package:json_annotation/json_annotation.dart';
part 'order.g.dart';
enum OrderStatus {
pending,
shipped,
cancelled,
}
@JsonSerializable()
class Order {
const Order({
required this.id,
required this.status,
});
factory Order.fromJson(Map<String, dynamic> json) =>
_$OrderFromJson(json);
final int id;
final OrderStatus status;
Map<String, dynamic> toJson() => _$OrderToJson(this);
}Run the generator after creating the file:
dart run build_runner build --delete-conflicting-outputsThe generated code maps "shipped" to OrderStatus.shipped and converts that value back to "shipped".
Mapping enum values to an API contract
An API may use names that do not match your Dart names. Use @JsonValue on an enum member when one value needs an explicit wire representation.
@JsonEnum(fieldRename: FieldRename.screamingSnake)
enum OrderStatus {
pending,
shipped,
@JsonValue('cancelled_by_user')
cancelled,
}fieldRename changes the other values to uppercase snake case:
pendingbecomes"PENDING".shippedbecomes"SHIPPED".cancelledremains"cancelled_by_user"because@JsonValuetakes precedence.
This lets your Dart code use readable names while following an existing API contract.
Handling unknown enum values
Servers sometimes add enum values before your app is updated. A direct conversion can then throw an exception. Add a fallback enum value and configure the field with unknownEnumValue.
enum PaymentState {
pending,
paid,
failed,
unknown,
}
@JsonSerializable()
class Payment {
const Payment({required this.state});
factory Payment.fromJson(Map<String, dynamic> json) =>
_$PaymentFromJson(json);
@JsonKey(unknownEnumValue: PaymentState.unknown)
final PaymentState state;
Map<String, dynamic> toJson() => _$PaymentToJson(this);
}If the server sends "refunded", deserialization produces PaymentState.unknown instead of failing. This is useful when displaying a safe fallback, but it can hide a server-side contract change. Log or report unknown values when they affect business decisions.
Testing enum mappings
Test both normal and custom values. A round-trip test checks that a Dart object survives conversion to JSON and back.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('serializes the custom cancelled value', () {
const order = Order(id: 7, status: OrderStatus.cancelled);
final json = jsonDecode(jsonEncode(order.toJson()))
as Map<String, dynamic>;
expect(json['status'], 'cancelled_by_user');
expect(Order.fromJson(json).status, OrderStatus.cancelled);
});
}Exercise
What JSON value should OrderStatus.cancelled produce when it has @JsonValue('cancelledbyuser')?
Show answer
It should produce "cancelledbyuser", even if a class-level fieldRename option would produce a different value.