Sub topic 4
Writing an annotated model class
This chapter assumes you can write Dart classes with constructors and null safety. It also assumes your project already has json_annotation, json_serializable, and build_runner installed, as covered in the previous chapter. Here you write the model class that the generator reads. The next chapter covers running the generator.
What an annotated model is
An annotated model is a plain Dart class with three additions:
- A
partdirective that links the class to a generated file. - The
@JsonSerializable()annotation on the class. - A
fromJsonfactory and atoJsonmethod that call functions the generator will write.
You write the class and the two small delegating members. The generator writes the code that reads and writes each field.
The minimal model
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
const User({required this.id, required this.name, this.email});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
final int id;
final String name;
final String? email;
Map<String, dynamic> toJson() => _$UserToJson(this);
}Save this as lib/models/user.dart. Until you run the generator, the editor shows errors on _$UserFromJson and _$UserToJson. That is expected, because those functions do not exist yet.
The parts of the file, one by one
The import
json_annotation is a regular dependency because the annotation classes (JsonSerializable, JsonKey, and others) ship with your app. The generator package json_serializable is a development dependency and never ends up in the app.
The part directive
part 'user.g.dart';A part directive makes another file a piece of this library. The generated file begins with part of 'user.dart';, so it can see private members of your library. This is why the generated functions have names starting with _$. A leading underscore makes them private to the library, so only user.dart can call them.
The file name must match your source file. For user.dart, the part is user.g.dart. If you rename the source file and forget the directive, the generator writes output to a name your code does not reference, and the compiler reports that the _$ functions are undefined.
The annotation
@JsonSerializable() tells the generator to produce code for this class. Without it, the generator skips the class. Options go inside the parentheses, for example @JsonSerializable(explicitToJson: true). Later chapters cover them. The defaults are enough for now.
The factory constructor
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);By convention, the factory is named fromJson and takes a Map<String, dynamic>. A factory constructor can return an instance built elsewhere, which fits here because the generated function builds the User. You call it as User.fromJson(map). The generator does not require this exact shape. It is a convention that keeps call sites uniform and lets other code, such as the generic support covered in a later chapter, find the constructor.
The toJson method
Map<String, dynamic> toJson() => _$UserToJson(this);The generated _$UserToJson is a top-level function that takes the instance as an argument. Your toJson method forwards this to it. The name toJson matters for a practical reason: jsonEncode calls toJson() on any object it does not know how to encode. So jsonEncode(user) works, and so does encoding a list of users, as long as each element has a toJson method.
What the generator produces
You do not edit the generated file, but reading it helps you predict behavior. For User, the output looks roughly like this:
part of 'user.dart';
User _$UserFromJson(Map<String, dynamic> json) => User(
id: (json['id'] as num).toInt(),
name: json['name'] as String,
email: json['email'] as String?,
);
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'email': instance.email,
};The exact formatting varies between package versions. Three behaviors follow from this code:
- The JSON key for each field is the field name.
idreadsjson['id']. - Each value is cast to the declared type. A cast is where a wrong type fails.
- The generated
toJsonwritesemail: nullwhen the field is null. It does not omit the key unless you configure that.
The diagram below shows how the pieces connect.
Which fields are serialized
The generator inspects the class and decides which members become JSON keys. The rules are:
| Member | Serialized? |
|---|---|
| Instance field that is a constructor parameter | Yes |
| Non-final instance field with no constructor parameter | Yes, assigned after construction |
| Final field with no constructor parameter | Written by `toJson`, but not read by `fromJson` |
| Private field (name starts with `_`) | No |
| Static field | No |
| Getter or setter pair without a backing field | No |
| Field with `@JsonKey(includeFromJson: false, includeToJson: false)` | No |
Two consequences matter in practice. First, a computed getter such as String get label => '$name ($id)'; is never written to JSON. Second, a private field is silently skipped, so a field named _token will not appear in the output. If you need a private-looking field in JSON, expose it under a public name.
Constructor requirements
The generated fromJson calls your constructor. This sets the rules:
- Every constructor parameter must correspond to a field of the same name. A parameter that matches no field produces a build error.
- Named and positional parameters both work, but named parameters are easier to read and to keep in sync.
- The constructor can be
const, and the fields can befinal. This is the preferred form because instances become immutable. - If the class has more than one generative constructor, the generator uses the unnamed one by default. You can choose another with
@JsonSerializable(constructor: 'named').
A mutable alternative also works, though it is less common in modern Dart:
import 'package:json_annotation/json_annotation.dart';
part 'settings.g.dart';
@JsonSerializable()
class Settings {
Settings();
factory Settings.fromJson(Map<String, dynamic> json) =>
_$SettingsFromJson(json);
bool darkMode = false;
String? language;
Map<String, dynamic> toJson() => _$SettingsToJson(this);
}Here the generated code calls Settings() and then assigns each field. Prefer the final-field version unless you need mutation.
Nullability decides what happens to missing keys
The Dart type of a field is also the schema for the JSON. Compare two fields from User:
final String name;is non-nullable. If the key is missing or the value isnull, the castjson['name'] as Stringthrows aTypeError.final String? email;is nullable. A missing key and an explicitnullboth givenull.
Marking a field required in the constructor only affects how Dart callers build the object. It does not make the JSON stricter than the type already does. Only the field type determines whether a missing key is tolerated. A later chapter on @JsonKey shows how to add defaults and to demand a key even for nullable fields.
Using the model
With the generated file in place, a small program shows both directions:
import 'dart:convert';
import 'package:my_app/models/user.dart';
void main() {
const raw = '{"id": 7, "name": "Grace", "email": null}';
final user = User.fromJson(jsonDecode(raw) as Map<String, dynamic>);
print(user.name); // Grace
print(jsonEncode(user)); // {"id":7,"name":"Grace","email":null}
}Replace my_app with the name in your pubspec.yaml. The as Map<String, dynamic> cast is needed because jsonDecode returns dynamic. jsonEncode(user) works because it calls user.toJson().
Common mistakes
| Symptom | Likely cause |
|---|---|
| `_$UserFromJson` is undefined | The generator has not run, or the `part` file name does not match |
| Build error about a constructor parameter | A constructor parameter has no matching field |
| Field missing from the output | The field is private, static, or excluded with `@JsonKey` |
| `type 'Null' is not a subtype of type 'String'` at runtime | A non-nullable field received a missing or null key |
| `type 'String' is not a subtype of type 'int'` at runtime | The JSON value type differs from the field type |
| Generator reports an unsupported type | The field type is a custom class without its own `fromJson`/`toJson`, or needs a `JsonConverter` |
Exercise
A class Product in lib/product.dart has the annotation @JsonSerializable(), a fromJson factory calling _$ProductFromJson, and the field final String _internalCode;. It also has a getter String get label => name.toUpperCase();. Which of these appear as keys in the output of toJson, and what must the part directive say?
Show answer
Neither _internalCode nor label appears. Private fields are skipped, and getters without a backing field are not serialized. The directive must be part 'product.g.dart';, matching the source file name.
Exercise
Given final int id; in a model, what happens when fromJson receives {"name": "Ada"} with no id key? How would you let the model accept this input?
Show answer
The generated cast of a null value to int throws a TypeError. To accept the input, make the field nullable (final int? id;) or give it a default with @JsonKey(defaultValue: ...).