json_serializable: Automating JSON in Dart
json_serializable is a boilerplate-writing robot for Dart, automatically generating code to convert classes to and from JSON. It's essential for data models in network requests or local storage.
Why it exists
Manually writing JSON serialization code (fromJson, toJson) is repetitive, tedious, and a major source of bugs. A typo in a JSON key string can cause silent failures at runtime. This process needed to be automated to improve developer productivity and ensure code is correct and maintainable.
The mental model
Think of json_serializable as a contract with a code-generating assistant. You define the shape of your data in a Dart class and add special instructions (annotations). The assistant then reads your instructions and writes the perfect, corresponding serialization logic in a separate file for you to use. You never touch the generated code; you just re-run the assistant when your class changes.
How it works
You add json_annotation as a dependency, and json_serializable plus build_runner as dev dependencies. First, you annotate a data class with @JsonSerializable. Second, you add a part 'my_file.g.dart'; directive at the top of your file. Third, you add the required hooks inside your class: a factory constructor factory YourClass.fromJson(Map<String, dynamic> json) => _YourClassFromJson(json); and a method Map<String, dynamic> toJson() => _YourClassToJson(this);. Finally, you run dart run build_runner build in your terminal. This command scans your project for annotations and generates the my_file.g.dart file containing the helper functions.
When to use it
Use it for virtually any plain data object in a Flutter or Dart application that needs to interact with JSON. This is standard practice for models representing API responses, data sent to a server, or objects persisted in local storage. It's especially valuable for complex, nested objects and handles type conversions (like String to DateTime) automatically.
When not to use it
For extremely simple, one-off cases with only one or two primitive fields, manual serialization might be faster than the initial build configuration setup. However, for any project of meaningful size, the setup cost pays for itself quickly. Avoid it if you have no control over the class you need to serialize (e.g., from a third-party package without its own support).
One canonical example
To make a Person class serializable, you annotate it and add the factory and method hooks:
@JsonSerializable()
class Person {final String firstName; final DateTime dateOfBirth;
Person({required this.firstName, required this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}After running the build runner, the generator creates the _$PersonFromJson function, which correctly maps the firstName string and parses the dateOfBirth from its ISO 8601 string format into a DateTime object.
Interview question
What is the primary function of the part 'my_file.g.dart'; directive in conjunction with json_serializable?
- a.It instructs the build_runner to fetch external JSON schemas for validation.
- b.It links the main class file to the automatically generated serialization and deserialization functions.Correct
- c.It specifies the output directory where build_runner should place all generated Dart files.
- d.It declares that the current file contains partial definitions for the json_annotation package.
Why? this is the answer
The 'part' directive is a Dart language feature that allows a file to include code from another file, making the generated serialization functions (like _YourClassFromJson) accessible to the main class. Option D is a tempting distractor because 'part' does relate to partial definitions, but it's for the generated code, not the json_annotation package itself.
Just read this? Test yourself on what you have been reading.
Read the original → pub.dev
- #dart
- #flutter
- #serialization
- #code generation
- #json
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on dart — each one lists the topics its interview covers.
See open roles