Sub topic 1
How JSON Maps to Dart with dart:convert
Prerequisites
This chapter assumes you know:
- Dart classes, constructors, and null safety
- Basic Flutter project structure and the
pubspec.yamlfile - Maps, lists, and generics in Dart
- The basic idea of calling a REST API that returns JSON
JSON Values and Dart Types
dart:convert is the core library for encoding and decoding JSON. jsonDecode turns a JSON string into ordinary Dart values:
- A JSON object becomes a
Map<String, dynamic>. - A JSON array becomes a
List<dynamic>. - Strings, numbers, booleans, and
nullbecomeString,intordouble,bool, andnull.
import 'dart:convert';
void main() {
const text = '{"id": 1, "name": "Ada", "email": null}';
final decoded = jsonDecode(text) as Map<String, dynamic>;
print(decoded['id'].runtimeType); // int
print(decoded['name']); // Ada
}Nothing in this map is typed beyond dynamic. The compiler cannot check key names or value types, so a typo like 'nmae' only fails at runtime.
Why Hand-Written Parsing Does Not Scale
You can convert the map into a model by hand:
class User {
User(this.id, this.name);
final int id;
final String name;
factory User.fromJson(Map<String, dynamic> json) =>
User(json['id'] as int, json['name'] as String);
}This works for two fields. With twenty fields, nested objects, and renamed keys, the code grows and every key string is a place for a mistake. Code generation avoids this work. You describe the model once, and a generator writes the conversion code.
> Callout note: Hand-written code is fine for one or two small models. Switch to generation when you copy the same pattern for a third model.
Adding the Packages
Run these commands in your project root. The annotation package is a regular dependency. The generator and runner are dev dependencies because the app does not need them at runtime.
flutter pub add json_annotation
flutter pub add dev:build_runner dev:json_serializableWriting an Annotated Model
Annotate the class with @JsonSerializable(). The part directive links the file to the generated code, which the generator writes to user.g.dart.
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
const User({required this.id, required this.name, this.email});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
final int id;
final String name;
final String? email;
Map<String, dynamic> toJson() => _$UserToJson(this);
}Run the generator once:
dart run build_runner build --delete-conflicting-outputsExercise
If you rename the field name to fullName in User and do not regenerate, which function will still use the old key, and what should you run to fix it?
Show answer
The _$UserFromJson and _$UserToJson functions in user.g.dart still reflect the old field, so you must rerun dart run build_runner build --delete-conflicting-outputs to regenerate them.