Summary - JSON
- Dart course
- Advanced
- Lesson 42/83
- 5 min
Combine jsonDecode, fromJson and json_serializable to write an API client.
Summary - JSON
This group covered JSON serialization in Dart: jsonDecode (String → dynamic), jsonEncode (object → String), fromJson (Map → class), toJson (class → Map), json_serializable (auto generation).
Core: jsonEncode does not accept a class directly; toJson is needed first. fromJson gives type-safe access. json_serializable auto-generates this code.
Symmetric design: fromJson(toJson(u)) == u. This gives a lossless serialization round-trip.
Practice Summary: decode + fromJson
Add import 'dart:convert';. Define class User { String name; User(this.name); factory User.fromJson(Map<String, dynamic> m) => User(m['name'] as String); }. Inside main add var u = User.fromJson(jsonDecode('{"name":"Ayşe"}') as Map<String, dynamic>); and print(u.name);.
Starter code
void main() {
// add dart:convert import; define User class with fromJson
// create an instance via jsonDecode + fromJson; print name
}Sample solution
import 'dart:convert';
class User {
String name;
User(this.name);
factory User.fromJson(Map<String, dynamic> m) => User(m['name'] as String);
}
void main() {
var u = User.fromJson(jsonDecode('{"name":"Ayşe"}') as Map<String, dynamic>);
print(u.name);
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does jsonEncode(u) do (u is a class)?
- Returns a Map
- Throws an error Correct answer
- Calls toJson automatically
- Empty String
Explanation: jsonEncode does not accept a class directly; it throws.
2 Match the concepts
| Term | Meaning |
|---|---|
jsonDecode |
String → dynamic |
jsonEncode |
Object → String |
fromJson |
Map → class |
toJson |
Class → Map |
3 Type cast
m['name'] ____ String
m['name'] as String
Explanation: 'as String' casts dynamic to String.