Sub topic 9
JSON with `fromJson` and `toJson`
Assume you know Dart classes, named parameters, null safety, and how to run terminal commands. This chapter shows how freezed works with json_serializable to convert immutable objects to and from JSON.
Why generated JSON code matters
JSON is a text-based data format commonly used by web APIs. Dart objects are convenient inside your app, but network responses arrive as maps and JSON strings. Serialization converts a Dart object into JSON-compatible values. Deserialization converts JSON-compatible values back into a Dart object.
Writing this conversion by hand becomes repetitive and can introduce mistakes when fields change. Code generation keeps the conversion aligned with your class definition.
Configure the generators
Add the annotation packages as regular dependencies. Add the generators and build_runner as development dependencies.
dart pub add freezed_annotation json_annotation
dart pub add --dev build_runner freezed json_serializablefreezed_annotation provides annotations such as @freezed. json_annotation provides annotations such as @JsonKey. The generator packages create the implementation files.
Add `fromJson` and `toJson`
The model needs two part directives. The first includes Freezed's generated implementation. The second includes the JSON conversion code generated by json_serializable.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
part 'person.g.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
@Default(0) int age,
@JsonKey(name: 'e_mail') String? email,
}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) =>
_$PersonFromJson(json);
}The fromJson factory is the public entry point used by your application. The generated function, _$PersonFromJson, does the field mapping. Freezed and json_serializable generate the private implementation and toJson method.
Run the generator after creating or changing the model:
dart run build_runner build --delete-conflicting-outputsThe command creates person.freezed.dart and person.g.dart. Do not edit these files. They are generated artifacts and may be replaced on the next build.
Use the model
void main() {
final person = Person.fromJson({
'name': 'Ada',
'age': 36,
'e_mail': '[email protected]',
});
print(person.email); // [email protected]
final json = person.toJson();
print(json['e_mail']); // [email protected]
}@JsonKey(name: 'e_mail') connects the API key e_mail to the Dart property email. This is useful when an API uses snake case or a name that conflicts with Dart conventions.
A field marked required must be present and have a compatible value during deserialization. The @Default(0) annotation supplies 0 when age is absent. A nullable field can contain null, depending on the generated conversion and the input data.
| Dart declaration | JSON role |
|---|---|
| `required String name` | Required string field |
| `@Default(0) int age` | Integer with a default |
| `String? email` | Nullable field |
| `@JsonKey(name: 'e_mail')` | Renamed JSON key |
Common errors
If the compiler reports that person.freezed.dart or person.g.dart is missing, run build_runner. If the generated code is stale, run the build again with --delete-conflicting-outputs.
The file name in each part directive must match the Dart file name exactly. For a file named person.dart, use person.freezed.dart and person.g.dart.
When an API's JSON shape differs from your model, solve the mismatch with annotations or a separate DTO model. Do not silently cast unrelated values. A generated parser makes type errors visible instead of hiding them.
Exercise
Which two declarations must be added to a Freezed model to generate JSON support, and what command creates the generated files?
Show answer
Add part 'model.g.dart'; and a factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);. Run dart run build_runner build --delete-conflicting-outputs.