Sub topic 6
Customizing fields with `@JsonKey`
Assume you know Dart classes, named constructors, null safety, and the basic json_serializable setup. This chapter focuses on controlling how one Dart field maps to one JSON key. The generated code still performs the conversion, but @JsonKey supplies the rules.
Renaming a JSON key
APIs often use names that do not match Dart style. For example, an API might send user_id, while your Dart class uses userId. Put @JsonKey(name: ...) directly above the field.
import 'package:json_annotation/json_annotation.dart';
part 'profile.g.dart';
@JsonSerializable()
class Profile {
const Profile({
required this.userId,
required this.displayName,
});
factory Profile.fromJson(Map<String, dynamic> json) =>
_$ProfileFromJson(json);
@JsonKey(name: 'user_id')
final int userId;
@JsonKey(name: 'display_name')
final String displayName;
Map<String, dynamic> toJson() => _$ProfileToJson(this);
}The annotation affects both directions:
| Dart field | JSON key when reading and writing |
|---|---|
| `userId` | `user_id` |
| `displayName` | `display_name` |
Generated fromJson reads json['user_id'], and generated toJson writes the same key. You do not need separate names for input and output.
Defaults and missing values
Use defaultValue when an older server response might omit a field. The value is used when the key is absent. It is not automatically used when the key exists with a JSON null.
@JsonSerializable()
class Settings {
const Settings({
required this.username,
this.notificationsEnabled = true,
});
factory Settings.fromJson(Map<String, dynamic> json) =>
_$SettingsFromJson(json);
final String username;
@JsonKey(defaultValue: true)
final bool notificationsEnabled;
Map<String, dynamic> toJson() => _$SettingsToJson(this);
}If notificationsEnabled is missing, deserialization produces true. If the API sends null, a non-nullable bool can still cause an error. Decide whether the field should be nullable or whether the server contract should reject null.
Required JSON keys
Dart's required keyword requires a constructor argument when your own code creates an object. It does not always require that a JSON key exists. Add required: true to make generated deserialization reject a missing key.
@JsonSerializable()
class Account {
const Account({required this.id, required this.email});
factory Account.fromJson(Map<String, dynamic> json) =>
_$AccountFromJson(json);
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String email;
Map<String, dynamic> toJson() => _$AccountToJson(this);
}Use this option for fields that are essential to the API contract. Do not use it for optional fields that older servers may omit.
Understanding the generated decision
Choosing an annotation
Use name for mismatched key names, defaultValue for backward-compatible omissions, and required for contract violations. Keep these rules close to the field so the model documents the API mapping.
Exercise
An API sends is_admin, and the key may be missing. Missing values should become false. Which annotation belongs on the Dart field?
Show answer
Use @JsonKey(name: 'is_admin', defaultValue: false) on a non-nullable bool isAdmin field.