toJson
- Flutter course
- Intermediate
- Lesson 58/99
- 4 min
Serialize a model to JSON with toJson.
The toJson method
To convert a model to JSON you write a toJson method. It returns a Map<String, dynamic>; the keys are JSON field names and the values are the model's fields. You can turn the returned Map into a JSON string with jsonEncode.
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
Map<String, dynamic> toJson() {
return {'ad': ad, 'yas': yas};
}
}
final k = Kullanici('Ada', 19);
print(jsonEncode(k.toJson()));
// {"ad":"Ada","yas":19}When is toJson useful?
toJson usually contains a simple return statement; you write each field as a key-value pair inside the Map. This method is especially useful before sending data to a server or storing it with shared_preferences.
Map<String, dynamic> toJson() {
return {
'ad': ad,
'yas': yas,
};
}Practice Write the toJson method
Add a toJson method to the Kullanici class. In main, convert the toJson output of k to a JSON string with jsonEncode and print it with print.
Starter code
import 'dart:convert';
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
// toJson metodunu buraya yaz
}
void main() {
final k = Kullanici('Cem', 35);
// k'nin toJson çıktısını jsonEncode ile yazdır
}Sample solution
import 'dart:convert';
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
Map<String, dynamic> toJson() {
return {'ad': ad, 'yas': yas};
}
}
void main() {
final k = Kullanici('Cem', 35);
print(jsonEncode(k.toJson()));
}Expected output
{"ad":"Cem","yas":35}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the return type of the toJson method?
- Map<String, dynamic> Correct answer
- Future
- void
- String
Explanation: toJson returns a Map; this Map is later converted to a JSON string with jsonEncode. void returns nothing, String is not direct, and it is not async.
2 Write the toJson body
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
Map<String, dynamic> toJson() {
____;
}
}
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
Map<String, dynamic> toJson() {
return {'ad': ad, 'yas': yas};
}
}
Explanation: toJson returns a Map; you write a Map literal with key-value pairs after return.
3 toJson parts
| Term | Meaning |
|---|---|
Map<String, dynamic> |
Return type |
'ad': ad |
Key-value pair |
return {...} |
Map return |
jsonEncode |
Conversion to JSON string |