Sub topic 7
Class-level options: naming and null handling
This chapter covers the settings on @JsonSerializable that apply to every field in a class: how Dart field names become JSON keys, and what happens to null values in each direction. It assumes you can annotate a model and run build_runner, and that you know @JsonKey from the previous chapter. It also assumes you are comfortable with Dart null safety.
Why class-level options exist
Most APIs follow one naming convention. If a backend sends order_id, created_at, and display_name, you could put @JsonKey(name: 'order_id') on every field. That is repetitive, and one forgotten annotation causes a runtime error. A class-level option states the convention once.
The same applies to null handling. You usually want one policy per model, such as "never send keys whose value is null", and not a decision per field.
Renaming fields with fieldRename
The fieldRename option takes a value of the FieldRename enum. The generator applies it to each field name that has no explicit @JsonKey(name: ...).
| Value | Dart field | JSON key |
|---|---|---|
| `FieldRename.none` (default) | `orderId` | `orderId` |
| `FieldRename.snake` | `orderId` | `order_id` |
| `FieldRename.kebab` | `orderId` | `order-id` |
| `FieldRename.pascal` | `orderId` | `OrderId` |
| `FieldRename.screamingSnake` | `orderId` | `ORDER_ID` |
The renaming applies in both directions. fromJson reads order_id, and toJson writes order_id. The Dart field name stays orderId, so your Flutter code follows Dart style.
import 'package:json_annotation/json_annotation.dart';
part 'profile.g.dart';
@JsonSerializable(fieldRename: FieldRename.snake, includeIfNull: false)
class Profile {
const Profile({
required this.userId,
required this.displayName,
this.avatarUrl,
this.bio,
});
factory Profile.fromJson(Map<String, dynamic> json) =>
_$ProfileFromJson(json);
final int userId;
final String displayName;
final String? avatarUrl;
final String? bio;
Map<String, dynamic> toJson() => _$ProfileToJson(this);
}After running dart run build_runner build --delete-conflicting-outputs, this code works:
import 'dart:convert';
import 'profile.dart';
void main() {
const profile = Profile(userId: 7, displayName: 'Ada');
print(jsonEncode(profile.toJson()));
// {"user_id":7,"display_name":"Ada"}
final parsed = Profile.fromJson(
jsonDecode('{"user_id": 7, "display_name": "Ada", "bio": "Hi"}')
as Map<String, dynamic>,
);
print(parsed.bio); // Hi
}The first output has no avatar_url or bio key. That comes from includeIfNull: false, which the next sections cover.
Naming gotchas
- Acronyms split badly. The snake conversion inserts an underscore before every uppercase letter. A field named
userIDbecomesuser_i_d, notuser_id. Name the fielduserId, or set the key by hand with@JsonKey(name: 'user_id'). - Digits stay attached.
address2becomesaddress2, notaddress_2. If the API sendsaddress_2, use an explicit@JsonKey(name: 'address_2'). - An explicit name wins.
@JsonKey(name: ...)always overridesfieldRename, so you can apply a class-wide convention and still handle the one field that breaks it. - The convention must be consistent.
fieldRenamecannot handle a payload that mixesorder_idandcreatedAt. Rename only the inconsistent fields with@JsonKey.
The generator resolves each key in a fixed order:
Null handling when writing JSON
By default, toJson writes every field, including those whose value is null. A Profile with no bio produces "bio": null.
Setting includeIfNull: false on the class makes the generated code skip any key whose value is null. The generated function builds the map first, then adds nullable entries only when they are non-null. Non-nullable fields are always written.
Skipping nulls is useful for these cases:
- Smaller payloads. A model with many optional fields sends only the ones that are set.
- Strict servers. Some backends reject
nullfor a field but accept its absence. - Partial updates. A
PATCHrequest that sends only the fields you changed.
You can override the class setting for one field:
@JsonSerializable(includeIfNull: false)
class Settings {
const Settings({this.theme, this.nickname});
factory Settings.fromJson(Map<String, dynamic> json) =>
_$SettingsFromJson(json);
final String? theme;
// Always sent, even when null, so the server can clear the nickname.
@JsonKey(includeIfNull: true)
final String? nickname;
Map<String, dynamic> toJson() => _$SettingsToJson(this);
}With Settings() both fields are null, and toJson() returns {nickname: null}. The theme key is omitted.
The "absent versus null" limit
After includeIfNull: false, the output cannot say "set this field to null". A missing key and a null value look the same, because both are omitted. If your API treats those cases differently, as many PATCH endpoints do, keep includeIfNull: true on the fields that must be clearable, as nickname does above. Another option is to build the patch body as a plain Map for those calls.
Null handling when reading JSON
Reading is governed by the Dart types, not by includeIfNull.
- A nullable field (
String?) becomesnullwhen the key is absent or its value isnull. - A non-nullable field with no default (
String) throws when the key is absent or its value isnull. The error is aTypeErrorsuch astype 'Null' is not a subtype of type 'String' in type cast. - A non-nullable field with a
@JsonKey(defaultValue: ...)falls back to the default when the key is absent.
A required constructor parameter and a non-nullable field work together. Mark a field nullable only when the API can really omit it. A nullable field that is always present adds ?. checks to your widgets for no benefit.
Rejecting unexpected keys
Two more class-level options make parsing stricter:
disallowUnrecognizedKeys: truemakesfromJsonthrow anUnrecognizedKeysExceptionwhen the JSON contains a key the class does not know. This catches typos and API changes early. Use it in tests and in internal tools. Be careful with it in production, because a server that adds a harmless new field would then break your app.checked: truewraps each field read so that failures become aCheckedFromJsonExceptionthat names the class and key. The error-handling chapter covers this in detail.
Applying options to every class with build.yaml
If all your models share a convention, set the options once in build.yaml at the project root instead of on each annotation. The keys use snake_case versions of the annotation parameters.
targets:
$default:
builders:
json_serializable:
options:
field_rename: snake
include_if_null: false
explicit_to_json: trueOptions in build.yaml set the defaults for every class in the package. An annotation on a class overrides them for that class. After you change build.yaml, rerun the generator, because existing .g.dart files do not update by themselves.
dart run build_runner build --delete-conflicting-outputsThe trade-off is visibility. With annotations, a reader sees the convention next to the class. With build.yaml, the behavior is hidden in another file. For a team, a common choice is to put package-wide conventions in build.yaml and to annotate only the exceptions.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `type 'Null' is not a subtype of type 'int'` on a field that exists in the API | The API key is `order_id` but no `fieldRename` or `@JsonKey(name:)` is set | Add `fieldRename: FieldRename.snake` or an explicit name |
| Key written as `user_i_d` | Field named `userID` with snake renaming | Rename the field to `userId` |
| `null` keys still appear in output | The option was set in `build.yaml` but the code was not regenerated, or a field has `@JsonKey(includeIfNull: true)` | Rerun `build_runner`, then check field-level overrides |
| A field cannot be set to null on the server | `includeIfNull: false` drops the key | Set `includeIfNull: true` on that field |
| New server field crashes the app | `disallowUnrecognizedKeys: true` in production | Use it only in tests and debug builds |
Summary of decisions
- Pick one
fieldRenamevalue that matches your API. Use@JsonKey(name:)for the exceptions. - Make a field nullable only if the API can omit it or send
null. - Use
includeIfNull: falseto shrink payloads and satisfy strict servers. Keeptrueon fields that must be clearable. - Use
disallowUnrecognizedKeyswhere you want API drift to fail loudly, not in released apps. - Move conventions shared by all models into
build.yaml.
Exercise
An API sends {"shipping_address": "1 Main St", "zip_code": "12345", "apartmentNo": "4B"}. Your class is annotated with @JsonSerializable(fieldRename: FieldRename.snake) and has fields shippingAddress, zipCode, and apartmentNo. What goes wrong when you call fromJson, and how do you fix it without changing the class-level option?
Show answer
With snake renaming, the generator looks for the key apartment_no, but the API sends apartmentNo. If the field is non-nullable, fromJson throws a type error because the value is null. If it is nullable, the field silently stays null. The fix is to annotate only that field with @JsonKey(name: 'apartmentNo'). An explicit name overrides fieldRename, so the other two fields still map to shipping_address and zip_code.
Exercise
A model has @JsonSerializable(includeIfNull: false) and a field final String? nickname;. A user wants to clear their nickname, and the server only clears it when it receives "nickname": null. Why does the update fail, and what is the smallest change that fixes it?
Show answer
With includeIfNull: false the generated toJson omits the nickname key when the value is null, so the server sees no change. Add @JsonKey(includeIfNull: true) to the nickname field, then regenerate the code. The field is then always written, including as null, and the rest of the class still omits nulls.