Sub topic 11
Handling malformed JSON and checked mode
This chapter assumes you can write a @JsonSerializable model, run build_runner, and call jsonDecode. It covers what fails when a server sends bad data, which exceptions you will see, and how checked: true turns vague errors into useful ones.
Where parsing can fail
Parsing a response has two stages, and each fails differently.
jsonDecodeturns text intoMap,List, and primitive values. It fails if the text is not valid JSON.- The generated
fromJsonturns those values into your model. It fails if the structure does not match your class.
Handling the two stages separately gives you clearer error messages. A truncated download is a transport problem. A renamed field is a contract problem.
What goes wrong without checked mode
By default the generated code uses plain Dart casts. A field declared int id is read as json['id'] as int. If the server sends "id": "7", you get a TypeError like type 'String' is not a subtype of type 'int' in type cast. The message names the types but not the field or the class. In a model with 30 fields, that is slow to debug.
There is a second problem. TypeError is an Error, not an Exception. A handler written as on Exception catch (e) will not catch it, and the error will escape your repository layer.
| Failure | Raised by | Type | Notes |
|---|---|---|---|
| Truncated or non-JSON text | `jsonDecode` | `FormatException` | Includes the offset of the bad character. |
| Top-level value is a `List`, not a `Map` | your cast, or `fromJson` | `TypeError` | Common when an API returns an error array. |
| Wrong value type | generated cast | `TypeError` | Names types, not fields. |
| Null for a non-nullable field | generated cast | `TypeError` | Looks like a wrong-type error. |
| Unparsable date string | `DateTime.parse` | `FormatException` | Raised from inside `fromJson`. |
| Unknown enum string | generated enum lookup | `ArgumentError` | Unless `unknownEnumValue` is set. |
Turning on checked mode
Set checked: true on the annotation. The generator wraps construction in a helper that records which key was being read. If anything fails, it throws a CheckedFromJsonException that carries that context.
Checked mode adds some overhead, because each field read goes through a wrapper closure. Most apps will not notice it. If you want it everywhere, set it in build.yaml instead of annotating each class:
targets:
$default:
builders:
json_serializable:
options:
checked: trueA CheckedFromJsonException exposes these properties:
keyis the JSON key being processed when the failure happened. It can be null.messageis a readable description of the problem.classNameis the name of the model being built.innerErroris the original error, such as theTypeError.mapis the JSON map that was being parsed.badKeyis true when the failure was about key presence (missing, unexpected, or disallowed null) and not a value's type.
It implements Exception, so on Exception catches it. That is one reason checked mode helps at an API boundary.
Making the contract stricter
Two more options let you reject payloads that silently "work" but are wrong. Both are @JsonKey or @JsonSerializable settings.
@JsonKey(required: true)fails if the key is absent from the map. A key present with a null value does not trigger it. Withoutrequired, a missing key and an explicit null look the same to a nullable field.@JsonKey(disallowNullValue: true)fails if the key is present with a null value.@JsonSerializable(disallowUnrecognizedKeys: true)fails if the map has keys the class does not know. This is useful in tests that guard against API drift. It is risky in production, because a server adding a harmless field would break every installed app.
These checks throw subclasses of BadKeyException: MissingRequiredKeysException, DisallowedNullValueException, and UnrecognizedKeysException. With checked: true, they arrive wrapped in a CheckedFromJsonException with badKey set to true.
For optional data, prefer tolerance. @JsonKey(defaultValue: ...) supplies a value when the key is missing or null. @JsonKey(unknownEnumValue: ...) maps an unrecognized enum string to a fallback instead of throwing.
A model that fails clearly
This model requires id and name, tolerates new plan names, and reports errors with context.
import 'package:json_annotation/json_annotation.dart';
part 'account.g.dart';
enum Plan { free, pro }
@JsonSerializable(checked: true)
class Account {
const Account({
required this.id,
required this.name,
required this.plan,
});
factory Account.fromJson(Map<String, dynamic> json) =>
_$AccountFromJson(json);
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String name;
@JsonKey(defaultValue: Plan.free, unknownEnumValue: Plan.free)
final Plan plan;
Map<String, dynamic> toJson() => _$AccountToJson(this);
}Now write one function that is the only place raw text becomes an Account. Callers then deal with a single exception type.
import 'dart:convert';
import 'account.dart';
class ApiParseException implements Exception {
const ApiParseException(this.message, {this.field});
final String message;
final String? field;
@override
String toString() => field == null
? 'ApiParseException: $message'
: 'ApiParseException: $message (field: $field)';
}
Account parseAccount(String body) {
final Object? decoded;
try {
decoded = jsonDecode(body);
} on FormatException catch (e) {
throw ApiParseException('Response is not valid JSON: ${e.message}');
}
if (decoded is! Map<String, dynamic>) {
throw ApiParseException(
'Expected a JSON object but got ${decoded.runtimeType}',
);
}
try {
return Account.fromJson(decoded);
} on CheckedFromJsonException catch (e) {
throw ApiParseException(
e.message ?? 'Invalid ${e.className} payload',
field: e.key,
);
}
}
void main() {
const samples = [
'{"id": 1, "name": "Ada", "plan": "pro"}',
'{"id": 1, "name": "Ada", "plan": "enterprise"}',
'{"id": "1", "name": "Ada"}',
'{"name": "Ada"}',
'[{"id": 1}]',
'{"id": 1, "name": ',
];
for (final body in samples) {
try {
final account = parseAccount(body);
print('ok: ${account.name} on ${account.plan.name}');
} on ApiParseException catch (e) {
print(e);
}
}
}The six samples show the behavior you now control:
- The first parses normally.
- The second falls back to
Plan.freebecause ofunknownEnumValue. - The third and fourth fail with the field named (
id). - The fifth fails on the top-level type check.
- The sixth fails in
jsonDecode.
The wording of message comes from the package, so avoid matching on it in logic. Use key, className, and badKey for decisions, and use message for logs.
Deciding how strict to be
Strictness is a trade-off between catching contract bugs early and surviving server changes.
- Use
required: truefor fields your UI cannot render without, such as identifiers. - Use nullable types or
defaultValuefor cosmetic fields. - Use
unknownEnumValueon every enum that the server owns, because servers add values. - Enable
disallowUnrecognizedKeysonly in tests against recorded payloads. - Convert failures to one app-level exception at the repository boundary, as
parseAccountdoes. UI code should not know aboutTypeErrororCheckedFromJsonException.
If you do not enable checked mode, catch TypeError explicitly (on TypeError catch (e)). Be aware that you lose the key name.
Exercise
A teammate wraps Account.fromJson in try { ... } on Exception catch (e) { ... } in a model that does not use checked: true. The server returns {"id": "5", "name": "Ada"}. What happens, and what two changes would make the failure both catchable and informative?
Show answer
The generated cast json['id'] as int throws a TypeError. TypeError is an Error, not an Exception, so the on Exception clause does not catch it and the error propagates. The message also names only types, not the field id. Two fixes: set checked: true on @JsonSerializable, so the failure becomes a CheckedFromJsonException (an Exception) with key == 'id', and catch that type at the boundary and rethrow a single app-level exception. Alternatively, catch TypeError explicitly, but then the key name is lost.
Exercise
Your API sometimes omits plan and sometimes sends "plan": "trial", a value the app does not know yet. Which two @JsonKey arguments let both payloads parse without exceptions, and which argument would you add to an id field to make a missing id an error?
Show answer
Use defaultValue (for example Plan.free) to cover a missing or null plan, and unknownEnumValue (for example Plan.free) to cover "trial". Add @JsonKey(required: true) to id so a missing key throws MissingRequiredKeysException, which checked mode wraps in a CheckedFromJsonException with badKey set to true.