Sub topic 1
How JSON Maps to Dart with `dart:convert`
Prerequisites
This chapter assumes you understand Dart classes, null safety, maps, lists, and basic REST API responses. You should also know that a JSON response is text until your program decodes it.
JSON, or JavaScript Object Notation, is a text format for structured data. A JSON object uses name-value pairs. A JSON array is an ordered list. Dart's dart:convert library converts between JSON text and Dart values.
The JSON-to-Dart mapping
The jsonDecode function reads a JSON string and returns a Dart value. The returned value has the type dynamic, so you must inspect or cast it before using it safely.
| JSON value | Dart value |
|---|---|
| Object, such as `{"id": 7}` | `Map<String, dynamic>` |
| Array, such as `[1, 2, 3]` | `List<dynamic>` |
| String | `String` |
| Number | `int` or `double` |
| `true` or `false` | `bool` |
| `null` | `null` |
A JSON object is usually the starting point for creating a Dart model. Its keys are strings, while its values can have different types. This is why the value type is commonly dynamic.
import 'dart:convert';
void main() {
const responseBody = '''
{
"id": 7,
"name": "Mina",
"admin": false,
"tags": ["flutter", "dart"]
}
''';
final decoded = jsonDecode(responseBody) as Map<String, dynamic>;
final id = decoded['id'] as int;
final name = decoded['name'] as String;
final isAdmin = decoded['admin'] as bool;
final tags = (decoded['tags'] as List<dynamic>)
.map((tag) => tag as String)
.toList();
print('$id: $name');
print('Admin: $isAdmin');
print('Tags: $tags');
}The as keyword performs a runtime type cast. If the response does not contain the expected type, the program throws a TypeError. This is useful during development because it exposes a contract mismatch instead of silently producing incorrect data.
A missing key returns null. A nullable field should therefore be cast to a nullable type:
final String? email = decoded['email'] as String?;A required field can be checked explicitly:
final rawId = decoded['id'];
if (rawId is! int) {
throw const FormatException('The response has no valid integer id');
}Encoding Dart values as JSON
The jsonEncode function converts Dart values into JSON text. It accepts JSON-compatible values such as maps, lists, strings, numbers, booleans, and null.
import 'dart:convert';
void main() {
final payload = <String, dynamic>{
'title': 'New task',
'completed': false,
'labels': ['work', 'today'],
};
final requestBody = jsonEncode(payload);
print(requestBody);
}jsonEncode does not automatically understand arbitrary Dart objects. A class must provide a JSON-compatible map, often through a toJson method. Later chapters use json_serializable to generate that method.
The complete data flow
Malformed JSON causes jsonDecode to throw a FormatException. Handle that exception at the network or repository boundary, where you can report a useful error or retry the request.
Exercise
What Dart type should you expect after decoding the JSON text [{"id": 1}, {"id": 2}]?
Show answer
List<dynamic>. Each element can then be checked or cast to Map<String, dynamic>.