Sub topic 15
Related tools and when to choose them
This chapter compares json_serializable with the other ways to turn JSON into Dart objects. It assumes you can already annotate a model, run build_runner, and read a generated .g.dart file, as covered in earlier chapters. It also assumes you know Dart 3 classes, records, and pattern matching at a basic level.
The goal is a decision. For each project, you should be able to say which approach fits and why.
The options at a glance
Every option answers the same question: where does the code that maps Map<String, dynamic> to your class come from?
- You write it by hand.
- A generator writes it from annotations (
json_serializable). - A generator writes it along with other class features (
freezed,built_value,dart_mappable). - A generator writes it from a schema outside Dart (OpenAPI, Protocol Buffers).
| Approach | Who writes the mapping | Extra features | Build step |
|---|---|---|---|
| Hand-written with patterns | You | None | No |
| `json_serializable` | Generator | Key, enum, and converter options | Yes |
| `freezed` + `json_serializable` | Generator | Immutability, `copyWith`, equality, unions | Yes |
| `dart_mappable` | Generator | Mapping, equality, `copyWith`, polymorphism | Yes |
| `built_value` | Generator | Immutable builders, its own serializer system | Yes |
| OpenAPI generators | Generator, from a spec | Whole client and models | Separate tool |
| Protocol Buffers | Generator, from `.proto` | Binary format, strict schemas | Separate tool |
Hand-written parsing, revisited
You saw earlier why hand-written parsing becomes fragile as models grow. Dart 3 changed how painful it is. Pattern matching lets you check the shape and the types in one expression.
import 'dart:convert';
class Tag {
const Tag(this.id, this.label);
factory Tag.fromJson(Object? json) {
if (json case {'id': int id, 'label': String label}) {
return Tag(id, label);
}
throw FormatException('Invalid Tag JSON', json);
}
final int id;
final String label;
Map<String, dynamic> toJson() => {'id': id, 'label': label};
}
void main() {
final tag = Tag.fromJson(jsonDecode('{"id": 7, "label": "dart"}'));
print('${tag.id} ${tag.label}');
}The if (json case {...}) pattern fails if a key is missing or has the wrong type. That gives you a clear FormatException with no casts. For a model with three to five fields, this is often less work than the setup for a generator.
Hand-written code stops being a good choice when:
- You have dozens of models, so the repeated boilerplate hides real logic.
- Both
fromJsonandtoJsonmust stay in sync with each field you add. - Several people edit the models, and a forgotten field in
toJsongoes unnoticed.
A forgotten field is the most common manual bug. The compiler cannot see it, because the map is built with string keys.
json_serializable on its own
Choose plain json_serializable when you want generated mapping and nothing else. Its strengths are:
- Small surface. It generates
_$XFromJsonand_$XToJsonand nothing more. Your class remains an ordinary Dart class. - Explicit options.
@JsonKey,fieldRename,JsonConverter, and@JsonEnumcover most real-world APIs. - Reviewable output. The
.g.dartfile is plain Dart. You can read it to see exactly how a field is parsed. - Official documentation support. The Flutter documentation describes it as a standard approach for larger projects.
Its limits are the reason the other tools exist:
- It does not generate
==,hashCode,copyWith, ortoString. You write those, or add another package. - It does not make your class immutable. You choose
finalfields yourself. - It has no built-in support for union (sealed) types beyond what you write manually.
- It needs the build step, so generated files can fall out of date until you rerun
build_runner.
freezed with json_serializable
freezed generates immutable data classes. It can also call json_serializable for the JSON part. You get value equality, copyWith, toString, and union types, and you still use fromJson and toJson.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile.freezed.dart';
part 'profile.g.dart';
@freezed
abstract class Profile with _$Profile {
const factory Profile({
required int id,
required String displayName,
@Default(false) bool verified,
}) = _Profile;
factory Profile.fromJson(Map<String, dynamic> json) =>
_$ProfileFromJson(json);
}This needs freezed_annotation as a regular dependency, and freezed and json_serializable alongside build_runner as development dependencies. The same dart run build_runner build command produces both generated files. Check the package's current documentation for exact version requirements, because freezed changed its class syntax between major versions.
Choose freezed when:
- Your state management relies on immutable objects and value equality, so comparing two states with
==has to work. - You want
copyWithon many models. - You model responses as unions, such as
Loading,Data, andError.
Skip it when you only need parsing. It adds a second generated file per class, longer build times, and one more package to upgrade.
Other generators
dart_mappable
dart_mappable generates mapping, equality, and copyWith from a single annotation. It also supports polymorphic classes and custom mappers. Consider it if you want one package to cover what json_serializable plus freezed cover together. The trade-off is that you move away from the most widely documented path. Fewer tutorials and Stack Overflow answers will match your setup.
built_value
built_value generates immutable classes with builders and its own serialization framework. It is strict and consistent, and it is also verbose. It suits large codebases that value that strictness. For a typical Flutter app, it is more ceremony than most teams want.
Generation from a schema
If your backend publishes an OpenAPI specification, tools such as the OpenAPI Generator can produce both models and an API client for Dart. The backend schema then becomes the single source of truth, and the models cannot drift from it. Protocol Buffers work the same way with a .proto file, and they use a compact binary format. Choose these when the schema already exists and multiple clients, such as web, mobile, and server, share it.
Macros
Dart's macros feature was meant to produce JSON code without a separate build step. The Dart team stopped work on it in 2025. Do not plan a project around it, and treat any tutorial that depends on it as out of date.
How to decide
Use these criteria when the diagram does not settle it:
- Count the models. A handful favors hand-written code. Dozens favor generation.
- Check what the rest of the app needs. If you already use
freezedfor state, add JSON to it. Don't run two systems side by side. - Look at API stability. An API that changes often is easier to follow with a generator. You change a field and rebuild, and mismatches then show up at compile time.
- Consider the team. A generator that the team knows well beats a more capable one nobody has used.
- Weigh build cost. Every generator adds build time and generated files to review and, depending on your team's convention, to commit.
Failure modes when switching
- Mixing generated and hand-written code in one class. If you add a field and forget to rerun
build_runner, the.g.dartfile silently ignores it. Rundart run build_runner watchduring development to avoid this. - Different default behavior between tools. Key naming, null handling, and
DateTimeformats are not guaranteed to match across packages. Check them after a migration. A round-trip test, as in the testing chapter, catches such changes quickly. - Committing generated files inconsistently. Decide as a team whether
.g.dartfiles are checked in or generated in CI, and apply the rule to every package. - Following outdated examples. Package APIs change between major versions. Read the changelog for the version you install rather than copying old snippets.
Exercise
Your app has 40 models from a REST API. The API has no published schema. The team uses plain immutable-style classes with manual == and copyWith, and wants to stop writing fromJson and toJson by hand. Which tool do you pick, and why not the alternatives?
Show answer
Pick json_serializable alone. The team only needs the JSON mapping, because it already has its own equality and copyWith. Hand-written parsing does not scale to 40 models. freezed would add a second generated file per class and replace code the team already has. A schema generator is not an option because no schema exists. If the team later wants to drop its manual == and copyWith, adding freezed becomes a reasonable second step.
Exercise
Why can a field forgotten in a hand-written toJson go unnoticed, and what protects you from it?
Show answer
The map is built from string keys, so the compiler cannot check that every field appears. A generator derives the output from the class fields, so a field cannot be left out. With hand-written code, a round-trip test that compares every field catches the omission.