Sub topic 6
Customizing fields with @JsonKey
The generated code from @JsonSerializable() assumes each Dart field maps to a JSON key of the same name and type. Real APIs often break that assumption: keys use a different style, fields are missing, or values arrive in an odd shape. @JsonKey lets you change how a single field is read and written, and the generator adjusts only that field's code.
This chapter assumes you can already annotate a model, run build_runner, and read a generated .g.dart file. It also assumes you know Dart null safety and how Map<String, dynamic> comes out of jsonDecode.
Where the annotation goes
Put @JsonKey(...) on the field declaration, not on the constructor parameter. The generator reads the annotation from the field and applies it to both directions of conversion, unless an option is specific to one direction.
@JsonKey(name: 'display_name')
final String displayName;Every argument to @JsonKey must be a compile-time constant, because annotations are evaluated at compile time. Where an option takes a function, it must be a top-level function or a static method, because only those can be referenced as constants.
The options at a glance
| Option | Affects | What it does |
|---|---|---|
| `name` | both | Uses a different JSON key for this field. |
| `defaultValue` | `fromJson` | Supplies a constant when the key is missing or `null`. |
| `required` | `fromJson` | Throws if the key is absent from the map. |
| `disallowNullValue` | `fromJson` | Throws if the key is present with a `null` value. |
| `includeIfNull` | `toJson` | When `false`, omits the key if the value is `null`. |
| `includeFromJson` | `fromJson` | When `false`, the field is not read from JSON. |
| `includeToJson` | `toJson` | When `false`, the field is not written to JSON. |
| `fromJson` / `toJson` | one each | Replaces the conversion with your own functions. |
| `readValue` | `fromJson` | Chooses how the raw value is pulled from the map. |
| `unknownEnumValue` | `fromJson` | Fallback for unrecognized enum strings (covered in the enums chapter). |
includeFromJson and includeToJson exist in current json_annotation releases. They replace the older ignore option, which is deprecated.
A model that uses most of them
The model below combines several options. The comments describe what each field expects in the JSON.
import 'package:json_annotation/json_annotation.dart';
part 'profile.g.dart';
List<String> _tagsFromJson(String json) =>
json.isEmpty ? <String>[] : json.split(',');
String _tagsToJson(List<String> tags) => tags.join(',');
Object? _readCity(Map<dynamic, dynamic> map, String key) =>
(map['address'] as Map<dynamic, dynamic>?)?['city'];
@JsonSerializable()
class Profile {
const Profile({
required this.id,
required this.displayName,
required this.loginCount,
required this.tags,
this.bio,
this.city,
this.sessionToken,
});
factory Profile.fromJson(Map<String, dynamic> json) =>
_$ProfileFromJson(json);
@JsonKey(required: true)
final int id;
@JsonKey(name: 'display_name')
final String displayName;
@JsonKey(defaultValue: 0)
final int loginCount;
@JsonKey(fromJson: _tagsFromJson, toJson: _tagsToJson)
final List<String> tags;
@JsonKey(includeIfNull: false)
final String? bio;
@JsonKey(readValue: _readCity)
final String? city;
@JsonKey(includeToJson: false)
final String? sessionToken;
Map<String, dynamic> toJson() => _$ProfileToJson(this);
}After running dart run build_runner build --delete-conflicting-outputs, this input works:
import 'dart:convert';
void main() {
const body = '''
{
"id": 7,
"display_name": "Ada",
"tags": "dart,flutter",
"address": {"city": "London"}
}
''';
final profile =
Profile.fromJson(jsonDecode(body) as Map<String, dynamic>);
print(profile.displayName); // Ada
print(profile.loginCount); // 0, from defaultValue
print(profile.tags); // [dart, flutter]
print(profile.city); // London
print(jsonEncode(profile.toJson()));
// {"id":7,"display_name":"Ada","loginCount":0,"tags":"dart,flutter","city":"London"}
}The output has no bio key because includeIfNull: false drops it. It has no sessionToken key because of includeToJson: false. The city key comes out at the top level, which the next sections explain.
Renaming keys with name
name is the simplest option. Use it when one key breaks a convention the rest of the payload follows, or when the JSON key is not a legal Dart identifier, such as "class" or "2fa".
If most keys need renaming in the same way, use fieldRename on @JsonSerializable instead. That option is covered in the class options chapter. An explicit name always wins over fieldRename for its field.
Defaults, required keys, and null values
These three options are easy to confuse because they all concern missing data. They answer different questions.
defaultValueanswers: what should the field be when the server sends nothing? It applies when the key is missing and also when the value isnull.required: trueanswers: is a missing key an error? The generated code throwsMissingRequiredKeysExceptionif the key is absent.disallowNullValue: trueanswers: is an explicitnullan error? The generated code throwsDisallowedNullValueExceptionif the key is present with anullvalue.
required checks that the key exists. It does not check the value. A key that is present with a null value passes the required check. If the field type is non-nullable, the cast then fails with a TypeError. Combine required: true with disallowNullValue: true when you want both checks to give a clear message.
The default must be a constant literal, such as 0, 'unknown', true, or const []. You cannot compute it at runtime. If you need a computed default, use a fromJson function or a normal constructor default.
Controlling what is written: includeIfNull
By default, toJson writes "bio": null for a null field. Some APIs reject null values or treat them as "clear this field". Setting includeIfNull: false on a field omits the key when the value is null. To apply this to every field in the class, set includeIfNull: false on @JsonSerializable instead. A @JsonKey on a field overrides the class setting for that field.
Excluding fields from one direction
includeFromJson: false and includeToJson: false act independently, and each fits a common case:
includeToJson: falsesuits values that exist only on the client, such as a session token or a cache timestamp. It also suits server-owned fields that must not be echoed back in a request.includeFromJson: falsesuits fields that the app computes after parsing.
A field excluded from fromJson must still be satisfiable when the generated code calls the constructor. Make it nullable and optional in the constructor, or give it a constructor default. Otherwise the generator reports an error at build time.
Custom conversion with fromJson and toJson
When one field needs special handling, a pair of functions is lighter than a full JsonConverter class. In the example, the server sends tags as one comma-separated string, and the model exposes a List<String>.
- The
fromJsonfunction takes the raw JSON value and returns the field type. - The
toJsonfunction takes the field value and returns somethingjsonEncodecan handle.
If the same conversion is needed on many fields or in many classes, write a JsonConverter instead. That is covered in a later chapter.
Reading from a different place with readValue
readValue runs before every other step for that field. It receives the whole map and the key, and returns whatever should be treated as the raw value. In the example, _readCity reaches into the nested address object, so the model can stay flat.
The order of events when reading
For a single field, the generated fromJson code works through the same steps in this order.
The diagram shows why defaultValue and required rarely belong together on one field. If a key is required, the generated code throws before a default could matter.
Common mistakes
- Annotation on the constructor parameter. It has no effect. Move it to the field.
- Non-constant default.
@JsonKey(defaultValue: DateTime.now())does not compile. Use afromJsonfunction. - Instance method as a converter. The
fromJsonandtoJsonoptions need a top-level function or astaticmethod. - Forgetting to regenerate. Changing a
@JsonKeyoption changes the.g.dartfile. Runbuild_runneragain, or keepdart run build_runner watchrunning. - Expecting
defaultValueintoJson. A null value stays null when writing, unless you also setincludeIfNull.
Exercise
A server sends {"id": 3, "nick": null}. Your model has @JsonKey(required: true) final int id; and @JsonKey(defaultValue: 'guest') final String nick;. What does fromJson produce for nick? Then, if the server instead omits id, what happens?
Show answer
nick becomes 'guest', because defaultValue applies when the value is null as well as when the key is missing. If id is omitted, the generated code throws a MissingRequiredKeysException before the constructor runs, because required: true rejects an absent key.
Exercise
You want a String? password field that is never written by toJson, and a List<String> roles field that the server sends as "admin;editor" and the model keeps as a list. Which @JsonKey options do you use for each?
Show answer
For password, use @JsonKey(includeToJson: false), and keep the field nullable and optional in the constructor. For roles, use @JsonKey(fromJson: _rolesFromJson, toJson: _rolesToJson), with top-level functions that split on ';' and join with ';'.