Summary - JSON parsing
- Flutter course
- Intermediate
- Lesson 55/99
- 4 min
Combine jsonDecode and nested access to handle API responses.
Decoding an API response as a whole
An API response usually mixes nested objects and arrays. First you decode the string into a Map<String, dynamic> with jsonDecode, then access fields with square brackets.
const yanit = '{"kullanici": {"ad": "Cem"}, "arkadaslar": ["Ali", "Veli"]}';
final m = jsonDecode(yanit) as Map<String, dynamic>;
print(m['kullanici']['ad']); // Cem
print((m['arkadaslar'] as List)[0]); // AliBecause the content can have mixed types, casting with as makes access safer.
Practice Process the API response
Decode the string yanit with jsonDecode. First print the 'ad' value, then print the first element of the 'arkadaslar' list with print.
Starter code
import 'dart:convert';
void main() {
const yanit = '{"ad": "Deniz", "arkadaslar": ["Selin", "Mert"]}';
// 'ad' değerini ve ilk arkadaşı yazdır
}Sample solution
import 'dart:convert';
void main() {
const yanit = '{"ad": "Deniz", "arkadaslar": ["Selin", "Mert"]}';
final m = jsonDecode(yanit);
print(m['ad']);
print((m['arkadaslar'] as List)[0]);
}Expected output
Deniz Selin
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If the 'arkadaslar' field in an API response is an array, how do you reach the first friend after jsonDecode?
- m['arkadaslar']['ad']
- m[0]['arkadaslar']
- jsonEncode(m['arkadaslar'])
- (m['arkadaslar'] as List)[0] Correct answer
Explanation: Since arkadaslar is an array, you first cast it to List and then access by index. jsonEncode serializes data instead of reading it; m['arkadaslar']['ad'] would require Map access; m[0] applies to a list, not to the root Map.
2 Get the second friend
import 'dart:convert';
void main() {
const s = '{"ad": "Cem", "arkadaslar": ["Ali", "Veli"]}';
final m = jsonDecode(s);
final ikinciArkadas = (m['arkadaslar'] as List)[____];
print(ikinciArkadas);
}
import 'dart:convert';
void main() {
const s = '{"ad": "Cem", "arkadaslar": ["Ali", "Veli"]}';
final m = jsonDecode(s);
final ikinciArkadas = (m['arkadaslar'] as List)[1];
print(ikinciArkadas);
}
Explanation: The second element has index 1; (m['arkadaslar'] as List)[1] gives 'Veli'.
3 JSON parsing summary
| Term | Meaning |
|---|---|
jsonDecode |
Converts a JSON string to a Map |
m['kullanici']['ad'] |
Reads a value from nested objects |
(m['arkadaslar'] as List)[0] |
Accesses the first element of the list |
dart:convert |
Library of jsonDecode and jsonEncode |