jsonEncode
- Dart course
- Advanced
- Lesson 38/83
- 5 min
Learn to produce JSON with jsonEncode.
jsonEncode
jsonEncode(obj) comes from dart:convert and turns a Dart object into JSON text. Map, List, String, num, bool, null are supported.
Example: var s = jsonEncode({'name': 'Ayşe', 'age': 30});. s is now the String {"name":"Ayşe","age":30}.
For your own classes, first convert to a Map with a toJson() method, then call jsonEncode. Passing a class directly throws.
String output format
jsonEncode output is single-line compact JSON: no spaces, keys double-quoted. {'a': 1} → {"a":1}.
For readable format use JsonEncoder.withIndent(' '): each key on a new line, indented. This is useful for debugging.
Special characters in String values are escaped: ' → \', newline → \n. This is done automatically.
Practice Encode a Map to JSON
Add import 'dart:convert';. Inside main add var s = jsonEncode({'name': 'Ayşe', 'age': 30});. Add print(s);.
Starter code
void main() {
// add dart:convert import; encode Map to JSON String; print
}Sample solution
import 'dart:convert';
void main() {
var s = jsonEncode({'name': 'Ayşe', 'age': 30});
print(s);
}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 Encode an object to JSON
var s = ____(data);
var s = jsonEncode(data);
Explanation: jsonEncode turns a Dart object into a JSON String.
2 Which type does jsonEncode NOT accept?
- Map
- User class Correct answer
- List
- int
Explanation: a user class is not accepted directly; toJson is needed first.
3 Match the encode parts
| Term | Meaning |
|---|---|
jsonEncode |
Object → String |
Map |
Input type |
toJson |
Class → Map |
JsonEncoder |
Custom output |