toJson
- Dart course
- Advanced
- Lesson 40/83
- 5 min
Learn to convert objects to JSON with toJson.
The toJson method
toJson is a method that turns a class instance into a JSON Map. jsonEncode does not call it automatically; you call it yourself.
Example: Map<String, dynamic> toJson() => {'name': name, 'age': age};. Then jsonEncode(u.toJson()) produces a JSON String.
For nested objects, toJson is chained: 'address': address.toJson(). For lists, items.map((i) => i.toJson()).toList().
Symmetric fromJson/toJson
In good design fromJson(toJson(u)) should equal the original instance. This is a lossless serialization round-trip, verified by tests.
Field names may differ in JSON: toJson returns {'user_name': name}, fromJson reads m['user_name']. The two must agree.
For versioned APIs, annotations like @JsonKey(name: 'legacy_name') are used (with json_serializable).
Practice Define User toJson
Define class User { String name; int age; User(this.name, this.age); Map<String, dynamic> toJson() => {'name': name, 'age': age}; }. Inside main add var u = User('Ayşe', 30);, add import 'dart:convert'; and print(jsonEncode(u.toJson()));.
Starter code
void main() {
// add dart:convert import; define User class with toJson
// create an instance; print via toJson + jsonEncode
}Sample solution
import 'dart:convert';
class User {
String name;
int age;
User(this.name, this.age);
Map<String, dynamic> toJson() => {'name': name, 'age': age};
}
void main() {
var u = User('Ayşe', 30);
print(jsonEncode(u.toJson()));
}Expected output
{"name":"Ayşe","age":30}
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)?
- Calls toJson automatically
- Returns a Map
- Returns an empty String
- Throws an error Correct answer
Explanation: jsonEncode does not accept a class directly; it throws.
2 Match the toJson parts
| Term | Meaning |
|---|---|
toJson() |
Class → Map |
Map<String, dynamic> |
Return type |
jsonEncode(u.toJson()) |
String production |
.map((i) => i.toJson()) |
List transform |
3 toJson return type
Map<String, dynamic> ____() => {'name': name};
Map<String, dynamic> toJson() => {'name': name};
Explanation: the toJson method returns Map<String, dynamic>.