Sub topic 11
Handling malformed JSON and checked mode
Assume you know Dart null safety, dart:convert, and how json_serializable generates fromJson methods. This chapter focuses on failures that happen when an API returns invalid text or a valid JSON value with the wrong shape.
JSON decoding has two separate stages:
jsonDecodeconverts a string into Dart values.User.fromJsonconverts those values into a typed Dart object.
A failure in the first stage usually means the text is not valid JSON. A failure in the second stage usually means a key is missing or its value has the wrong type.
| Failure | Typical cause | Useful response |
|---|---|---|
| `FormatException` | Broken JSON syntax | Report an invalid server response |
| `CheckedFromJsonException` | Wrong field type or missing required key | Log the field and reject the payload |
| Validation error | Valid type but unacceptable value | Apply application rules |
Enable checked generated code
Add checked: true to the model annotation. Add required: true when the JSON must contain a particular key.
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(checked: true)
class User {
const User({
required this.id,
required this.name,
this.email,
});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String name;
final String? email;
Map<String, dynamic> toJson() => _$UserToJson(this);
}
User parseUser(String responseBody) {
final decoded = jsonDecode(responseBody);
if (decoded is! Map<String, dynamic>) {
throw const FormatException('Expected a JSON object for User');
}
return User.fromJson(decoded);
}Regenerate the model after changing the annotation:
dart run build_runner build --delete-conflicting-outputsWithout checked mode, generated code can expose a lower-level cast or null error. With checked mode, json_serializable adds context about the class and field that failed. This makes logs and error handling more useful.
jsonDecode still runs before generated code. Therefore, checked mode cannot repair malformed syntax such as a missing quote or comma.
Handle errors at the boundary
Catch decoding errors close to the network or repository boundary. Do not let malformed server data reach widgets.
import 'package:json_annotation/json_annotation.dart';
User loadUser(String body) {
try {
return parseUser(body);
} on FormatException {
throw const FormatException('The server returned invalid JSON');
} on CheckedFromJsonException catch (error) {
throw FormatException('The user response has an invalid field: $error');
}
}Use defaultValue only when a missing field has a safe meaning. A default can hide a server regression. Also remember that checked mode does not validate business rules. A negative id or an empty required name can have the correct Dart type but still be invalid for your application.
Exercise
Which exception should you expect when the response text is { "id": 1, and which exception should you expect when id is the string "one" in checked generated code?
Show answer
The incomplete text causes jsonDecode to throw FormatException. The valid JSON with an incompatible id value causes checked generated code to throw CheckedFromJsonException.