Sub topic 2
Generating code with build_runner
This chapter assumes you know Dart null safety, have a Flutter project with a pubspec.yaml, and have added json_annotation, json_serializable, and build_runner as described in the previous chapter.
json_serializable writes the fromJson and toJson code for you. build_runner is the tool that runs it and writes the result to a .g.dart file beside your model.
Customizing fields with @JsonKey
@JsonKey changes how one field is read or written. Use name to set a different JSON key, and defaultValue to supply a value when the key is missing.
Class-level options: naming and null handling
@JsonSerializable accepts options that apply to every field in the class. fieldRename: FieldRename.snake turns teamName into team_name. includeIfNull: false omits null fields from the output instead of writing them as null.
Nested objects and lists
A field whose type is another serializable class needs that class to be annotated too. Set explicitToJson: true so that toJson converts nested objects, not just the outer class, into maps.
import 'package:json_annotation/json_annotation.dart';
part 'team.g.dart';
@JsonSerializable(
fieldRename: FieldRename.snake,
includeIfNull: false,
explicitToJson: true,
)
class Team {
const Team({required this.teamName, required this.members, this.website});
factory Team.fromJson(Map<String, dynamic> json) => _$TeamFromJson(json);
final String teamName;
final List<Member> members;
final String? website;
Map<String, dynamic> toJson() => _$TeamToJson(this);
}
@JsonSerializable()
class Member {
const Member({required this.userId, required this.role});
factory Member.fromJson(Map<String, dynamic> json) => _$MemberFromJson(json);
@JsonKey(name: 'user_ref')
final int userId;
@JsonKey(defaultValue: 'viewer')
final String role;
Map<String, dynamic> toJson() => _$MemberToJson(this);
}Run the generator from the project root:
dart run build_runner build --delete-conflicting-outputsExercise
In a class annotated with fieldRename: FieldRename.snake, a field named maxSize has @JsonKey(name: 'limit'). What key appears in toJson?
Show answer
'limit'. The explicit name takes priority over the class-level rename, so the snake_case rule does not apply to that field.