Sub topic 2
Why hand-written parsing does not scale
This chapter assumes you know Dart classes, constructors, and null safety. It also assumes you have used jsonDecode and know that decoded JSON arrives as Map<String, dynamic> and List<dynamic>. The goal is to see where hand-written fromJson and toJson code breaks down, so the generated code in the next chapters solves a problem you can name.
The baseline: a small hand-written model
For a model with three fields, manual parsing is reasonable. Here is a User with a fromJson factory and a toJson method:
class User {
const User({required this.id, required this.name, this.email});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String?,
);
}
final int id;
final String name;
final String? email;
Map<String, dynamic> toJson() => {'id': id, 'name': name, 'email': email};
}
void main() {
final ok = User.fromJson({'id': 1, 'name': 'Ada'});
print(ok.toJson());
try {
User.fromJson({'id': '1', 'name': 'Ada'});
} on TypeError catch (e) {
print('Failed: $e');
}
}The first call prints {id: 1, name: Ada, email: null}. The second throws a TypeError because '1' is a String and the code casts it to int.
The code is short and explicit, and it has no build step. For a handful of small models, that is a fair trade. The problems appear as the number and size of models grow.
Every field is written four times
A field in a hand-written model appears in four places:
- The field declaration.
- The constructor parameter.
- The
fromJsonentry. - The
toJsonentry.
The JSON key string appears in both fromJson and toJson, so each field carries two string literals that must match the server's spelling and each other. The compiler checks none of these strings. Dart does check the declaration and the constructor, but it cannot link 'created_at' to createdAt.
A realistic model
Real payloads contain nested objects, lists, enums, dates, and snake_case keys. Here is an order model written by hand. It uses the same fields that later chapters generate code for.
enum OrderStatus { pending, shipped, cancelled }
OrderStatus _statusFromJson(String value) {
switch (value) {
case 'pending':
return OrderStatus.pending;
case 'shipped':
return OrderStatus.shipped;
case 'cancelled_by_user':
return OrderStatus.cancelled;
default:
throw FormatException('Unknown order status: $value');
}
}
String _statusToJson(OrderStatus status) {
switch (status) {
case OrderStatus.pending:
return 'pending';
case OrderStatus.shipped:
return 'shipped';
case OrderStatus.cancelled:
return 'cancelled_by_user';
}
}
class LineItem {
const LineItem({required this.sku, this.quantity = 1});
factory LineItem.fromJson(Map<String, dynamic> json) {
return LineItem(
sku: json['sku'] as String,
quantity: json['quantity'] as int? ?? 1,
);
}
final String sku;
final int quantity;
Map<String, dynamic> toJson() => {'sku': sku, 'quantity': quantity};
}
class Order {
const Order({
required this.orderId,
required this.items,
required this.createdAt,
required this.status,
});
factory Order.fromJson(Map<String, dynamic> json) {
return Order(
orderId: json['order_id'] as int,
items: (json['items'] as List<dynamic>)
.map((e) => LineItem.fromJson(e as Map<String, dynamic>))
.toList(),
createdAt: DateTime.parse(json['created_at'] as String),
status: _statusFromJson(json['status'] as String),
);
}
final int orderId;
final List<LineItem> items;
final DateTime createdAt;
final OrderStatus status;
Map<String, dynamic> toJson() => {
'order_id': orderId,
'items': items.map((e) => e.toJson()).toList(),
'created_at': createdAt.toIso8601String(),
'status': _statusToJson(status),
};
}This is about 70 lines for four fields and one nested type. Two helper functions exist only to map one enum, and every conversion rule (cast, DateTime.parse, list mapping) is written by hand for each field. A project with 40 models of this kind has thousands of lines of code that carry no business logic.
How hand-written parsing fails
The cost is not only typing. Manual code fails in ways that are easy to introduce and hard to notice.
| Failure | Example | What you see |
|---|---|---|
| Key typo | `json['orderid']` instead of `json['order_id']` | A null cast error at runtime, far from the typo |
| Wrong cast | `as int` when the server sends `1.0` or `"1"` | `TypeError` at runtime |
| Nullability mismatch | `as String` on a field the server sometimes omits | `TypeError` on some responses only |
| Forgotten `toJson` entry | New field added to `fromJson` but not `toJson` | Silent data loss when saving |
| Forgotten `.toJson()` on nested items | `'items': items` instead of mapping | A map holding objects, not maps |
| Enum drift | Server adds a status, the `switch` lacks it | `FormatException` or wrong default |
Two of these deserve a closer look.
Silent data loss in toJson
Suppose a teammate adds a note field. They update the declaration, the constructor, and fromJson, then forget toJson:
class Ticket {
const Ticket({required this.id, this.note});
factory Ticket.fromJson(Map<String, dynamic> json) {
return Ticket(
id: json['id'] as int,
note: json['note'] as String?,
);
}
final int id;
final String? note;
// note is missing here. The compiler does not complain.
Map<String, dynamic> toJson() => {'id': id};
}The app reads the note correctly, so manual testing of the read path looks fine. Every save sends a payload without it, and the server may clear the value. No exception is raised.
The nested toJson trap
Writing 'items': items in toJson looks harmless. jsonEncode calls toJson() on objects it does not recognize, so encoding to a string still works. The map itself, however, holds LineItem objects. Code that compares that map in a test, stores it in a database layer, or passes it to a package expecting plain maps will misbehave. The generated code you will see later deals with this through the explicitToJson option.
Errors surface far from their cause
A hand-written parser usually throws a bare TypeError such as type 'Null' is not a subtype of type 'String' in type cast. The message does not name the key or the model. When a list of 200 items fails on item 137, you must find which field was wrong by debugging.
You can improve this by wrapping each field in checks and throwing a FormatException with the key name. Doing that for every field multiplies the code again, so most teams skip it. This is the usual state of manual parsing: the code is only as careful as its least careful author.
Maintenance cost grows with the API
The effort is not one-time. Each of these changes forces edits in several places per model:
- The backend renames a field, so you edit the key string in two places and the Dart name if you follow it.
- The backend changes naming style, for example from
camelCasetosnake_case, so every key string in every model changes. - A value moves from an integer to a string, so casts change and tests break.
- You need a default for a field that used to be required.
A fromJson written against yesterday's API continues to compile against today's. The mismatch shows up when a user opens the affected screen.
When manual parsing is still the right choice
Code generation adds a build step, generated files, and dependencies. Manual parsing is a sound choice in these cases:
- You have a few small models with flat structure.
- You parse a response once to read one or two values, such as
json['token']. - The payload shape is highly dynamic, and you need custom logic on most fields.
- You are prototyping, and the model may be discarded.
As a rough decision rule, consider generation once you have more than a few models, nested types, enums, or date fields, or when more than one person edits the models. At that point the repeated mapping code is the main source of bugs.
What a generator changes
Generated code removes the duplication rather than making you more careful. The field declaration becomes the single source of truth, and the generator writes the casts, the key strings, and the nested calls from it. Renaming the style of every key becomes one option on the class. Key and type mapping logic is emitted in the same way for every model, so a mistake made once is not repeated unevenly.
The generator does not remove the need to understand JSON types. It also does not guarantee that a server keeps its promises. It makes the mapping uniform and checkable, and the next chapters set up that tooling.
Exercise
A teammate adds a nullable phone field to a hand-written model and updates the declaration, the constructor, and fromJson. Tests that read data pass. Users report that phone numbers disappear after editing a profile. What most likely went wrong, and why did no tool catch it?
Show answer
The toJson method was not updated, so the new field is never sent when the profile is saved. The compiler cannot connect a key string in toJson to a field, and the read-path tests never exercise toJson. A round-trip test (encode, decode, compare fields) or generated code would catch it.
Exercise
Name three of the four places a field must be written in a hand-written model, and say which of them the Dart compiler cannot verify against the JSON.
Show answer
The field declaration, the constructor parameter, the fromJson entry, and the toJson entry. The compiler checks the declaration and the constructor. It cannot verify the key strings in fromJson and toJson against the JSON, and it does not check that a toJson entry exists at all.