Sub topic 7
Class-Level Options: Naming and Null Handling
This chapter assumes you know Dart classes, constructors, null safety, and the basic json_serializable workflow. You should also know that fromJson reads a Map<String, dynamic> and toJson creates one.
A class-level option changes how json_serializable treats all fields in a model. Two useful options are:
fieldRename, which converts Dart field names into JSON key names.includeIfNull, which controls whether fields withnullvalues appear in output JSON.
Converting Dart names to JSON names
Dart code commonly uses camelCase, while APIs often use snake_case. Instead of adding @JsonKey(name: ...) to every field, set fieldRename on @JsonSerializable.
import 'package:json_annotation/json_annotation.dart';
part 'profile.g.dart';
@JsonSerializable(fieldRename: FieldRename.snake)
class Profile {
const Profile({
required this.userId,
required this.displayName,
this.avatarUrl,
});
factory Profile.fromJson(Map<String, dynamic> json) =>
_$ProfileFromJson(json);
final int userId;
final String displayName;
final String? avatarUrl;
Map<String, dynamic> toJson() => _$ProfileToJson(this);
}The generated code maps the fields like this:
| Dart field | JSON key |
|---|---|
| `userId` | `user_id` |
| `displayName` | `display_name` |
| `avatarUrl` | `avatar_url` |
The rename rule applies when reading and writing. Therefore, fromJson expects user_id, not userId.
Other available values include FieldRename.none, FieldRename.kebab, and FieldRename.pascal. The default is FieldRename.none, which keeps the Dart field name.
Omitting null fields
By default, json_serializable includes nullable fields in the output:
{
"user_id": 7,
"display_name": "Ada",
"avatar_url": null
}Set includeIfNull: false to omit fields whose values are null:
@JsonSerializable(
fieldRename: FieldRename.snake,
includeIfNull: false,
)
class UpdateProfile {
const UpdateProfile({
required this.displayName,
this.avatarUrl,
this.bio,
});
factory UpdateProfile.fromJson(Map<String, dynamic> json) =>
_$UpdateProfileFromJson(json);
final String displayName;
final String? avatarUrl;
final String? bio;
Map<String, dynamic> toJson() => _$UpdateProfileToJson(this);
}For UpdateProfile(displayName: 'Ada'), toJson() produces:
{
"display_name": "Ada"
}includeIfNull affects serialization only. It does not make a missing JSON key valid for a non-nullable field. When decoding, a missing required field can still cause a runtime error.
Overriding one field
A field-level @JsonKey(name: ...) takes precedence over the class-level naming rule:
@JsonSerializable(fieldRename: FieldRename.snake)
class Account {
const Account({required this.userId, required this profileURL});
factory Account.fromJson(Map<String, dynamic> json) =>
_$AccountFromJson(json);
final int userId;
@JsonKey(name: 'profileImage')
final String profileURL;
Map<String, dynamic> toJson() => _$AccountToJson(this);
}Here, userId becomes user_id, but profileURL becomes profileImage.
After changing these annotations, regenerate the part file:
dart run build_runner build --delete-conflicting-outputsExercise
With @JsonSerializable(fieldRename: FieldRename.snake, includeIfNull: false), what JSON does Settings(themeMode: 'dark', locale: null).toJson() produce if the fields are themeMode and nullable locale?
Show answer
{"theme_mode": "dark"}. The naming rule changes themeMode to theme_mode, and includeIfNull: false removes locale.