← → or space · progress saves for Continue on the roadmap
Goal
Turn Dart values into JSON text and parse JSON text into Dart values.
Step 1 - Encode
import 'dart:convert';
void main() {
final map = {'name': 'Asha', 'score': 10};
final text = jsonEncode(map);
print(text);
}- JSON object keys become strings. Dart
Mapkeys must be strings forjsonEncode(or it throws).
Step 2 - Decode
import 'dart:convert';
void main() {
final text = '{"name":"Asha","score":10}';
final value = jsonDecode(text);
print(value.runtimeType);
print((value as Map)['name']);
}jsonDecodereturnsObject?at compile time; at runtime you usually getMap<String, dynamic>,List<dynamic>,String,num,bool, ornull.
Step 3 - Pretty print (optional)
import 'dart:convert';
void main() {
const encoder = JsonEncoder.withIndent(' ');
print(encoder.convert({'a': 1, 'b': [2, 3]}));
}Good habit
- Treat decoded data as untrusted: validate shape before using as your model.
Practice tasks
- Encode a
Listof maps and decode it back, then assert list length. - Try
jsonDecode('{bad')intry/catchand printFormatException.