Sub topic 1
How JSON maps to Dart with dart:convert
Every JSON serialization tool in Flutter sits on top of dart:convert. Before you generate any code, you need a clear picture of what that library returns, which types you get back, and where the type system stops helping you. This chapter builds that model and covers the errors you will hit first.
Prerequisites
This chapter assumes you already know:
- Dart classes, constructors, and null safety (
String?,required,ascasts). - Maps, lists, and generics in Dart, such as
Map<String, dynamic>andList<dynamic>. - The basic shape of a REST API that returns JSON in an HTTP response body.
- How a Flutter project is laid out, including
pubspec.yaml.
You do not need any packages for this chapter. dart:convert ships with the Dart SDK.
What JSON is, and what Dart gives you
JSON is a text format. A JSON document is always a string until you decode it. It has six kinds of value: object, array, string, number, boolean, and null.
The dart:convert library turns that text into ordinary Dart objects. The mapping is fixed:
| JSON value | Dart type after `jsonDecode` |
|---|---|
| object `{}` | `Map<String, dynamic>` |
| array `[]` | `List<dynamic>` |
| string | `String` |
| whole number such as `3` | `int` |
| number with a fraction or exponent such as `3.5` | `double` |
| `true` / `false` | `bool` |
| `null` | `null` |
Two details matter in practice. First, JSON has one number type, but Dart has two. The decoder picks int or double based on how the number is written, so 3 and 3.0 decode to different Dart types. Second, there is no JSON type for dates, enums, or sets. Those arrive as strings or numbers, and you must convert them yourself.
Decoding with jsonDecode
jsonDecode takes a String and returns dynamic. The static type is dynamic because the decoder cannot know the shape of your document.
import 'dart:convert';
void main() {
const body = '{"id": 1, "name": "Ada", "email": null, "tags": ["admin", "dev"]}';
final decoded = jsonDecode(body);
print(decoded.runtimeType); // _Map<String, dynamic>
final map = decoded as Map<String, dynamic>;
final id = map['id'] as int;
final name = map['name'] as String;
final email = map['email'] as String?;
final tags = (map['tags'] as List<dynamic>).cast<String>();
print('$id $name $email $tags'); // 1 Ada null [admin, dev]
}The casts are doing real work. Without as, a value read from the map has type dynamic, and the compiler accepts almost anything you do with it. A wrong guess then fails at run time instead of at compile time.
Why the list is `List<dynamic>`
A decoded array is typed List<dynamic>, even when every element is a string. You cannot write map['tags'] as List<String>, because the runtime object is a List<dynamic> and that cast throws. Use .cast<String>() or .map((e) => e as String).toList(). The first returns a lazy view that checks each element when read. The second copies the data and checks every element immediately, so a bad element fails at the point of conversion.
Encoding with jsonEncode
jsonEncode goes the other way. It accepts Dart objects and returns a String.
import 'dart:convert';
void main() {
final data = <String, dynamic>{
'id': 1,
'name': 'Ada',
'tags': ['admin', 'dev'],
'active': true,
'manager': null,
};
print(jsonEncode(data));
// {"id":1,"name":"Ada","tags":["admin","dev"],"active":true,"manager":null}
}jsonEncode only knows how to write the types in the table above. For anything else, it calls toJson() on the object. If the object has no toJson() method, you get a JsonUnsupportedObjectError.
import 'dart:convert';
class Point {
Point(this.x, this.y);
final int x;
final int y;
}
void main() {
try {
jsonEncode({'origin': Point(0, 0)});
} on JsonUnsupportedObjectError catch (e) {
print('Cannot encode: ${e.unsupportedObject.runtimeType}'); // Point
}
}This toJson() hook is the entry point that generated code will use later. A model class that defines Map<String, dynamic> toJson() can be placed directly inside a map or list passed to jsonEncode.
A DateTime has no toJson() that jsonEncode calls for you. Passing one raises the same error, so you convert it first, usually with toIso8601String().
Pretty printing
For logs, use JsonEncoder.withIndent.
import 'dart:convert';
void main() {
const encoder = JsonEncoder.withIndent(' ');
print(encoder.convert({'id': 1, 'tags': ['a', 'b']}));
}Do not send indented JSON over the network by default. The extra whitespace only increases the payload size.
The two-step pipeline
Decoding a network response involves two separate conversions. The first turns bytes into a string. The second turns the string into Dart objects. Most HTTP libraries do the first step for you, but the distinction matters for encoding problems.
The diagram below shows the full path.
When you have raw bytes, for example response.bodyBytes from the http package, decode them as UTF-8 yourself. Using response.body can apply the wrong character set when the server omits a charset header, which corrupts accented characters.
import 'dart:convert';
import 'dart:typed_data';
dynamic decodeBytes(Uint8List bytes) => jsonDecode(utf8.decode(bytes));You can also fuse the two steps with json.fuse(utf8), which avoids building the intermediate string.
import 'dart:convert';
import 'dart:typed_data';
final bytesToObject = json.fuse(utf8).decoder;
dynamic decodeFast(Uint8List bytes) => bytesToObject.convert(bytes);Reading a typical response
Real responses are rarely one flat object. A list endpoint often returns an array of objects. A single-resource endpoint often wraps the data in an envelope. Your code should decide on the top-level type first, then walk down.
import 'dart:convert';
class User {
const User({required this.id, required this.name, this.email});
final int id;
final String name;
final String? email;
}
List<User> parseUsers(String responseBody) {
final decoded = jsonDecode(responseBody) as List<dynamic>;
return decoded.map((e) {
final map = e as Map<String, dynamic>;
return User(
id: map['id'] as int,
name: map['name'] as String,
email: map['email'] as String?,
);
}).toList();
}
void main() {
const body = '[{"id":1,"name":"Ada","email":null},{"id":2,"name":"Lin"}]';
for (final user in parseUsers(body)) {
print('${user.id} ${user.name} ${user.email}');
}
}Notice that the second object has no email key at all. map['email'] returns null for a missing key, so a nullable cast handles both "key absent" and "key present with value null" the same way. When that difference matters, use map.containsKey('email').
Common errors
Most first-week failures come from a small set of causes.
| Symptom | Cause | Fix |
|---|---|---|
| `FormatException: Unexpected character` | The input is not valid JSON, for example an HTML error page or an empty body | Check the status code before decoding, and log the first part of the body |
| `type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>'` | The endpoint returned an object, but you cast to a list | Inspect the top-level shape and cast to the right type |
| `type 'Null' is not a subtype of type 'String'` in type cast | A required field is missing or `null` | Cast to `String?` and handle null, or reject the payload with a clear message |
| `type 'int' is not a subtype of type 'double'` | The server sent `5` for a price, and you cast to `double` | Use `(value as num).toDouble()` |
| `type 'List<dynamic>' is not a subtype of type 'List<String>'` | Direct cast of a decoded list | Use `.cast<String>()` or `.map(...).toList()` |
| `JsonUnsupportedObjectError` | `jsonEncode` met an object with no `toJson()` | Add `toJson()` or convert the value first |
The int versus double case deserves attention. A field such as price may be 9.99 in one response and 10 in the next. Casting to double works for the first and crashes on the second. Reading it as num and converting is the safe pattern.
double readPrice(Map<String, dynamic> json) => (json['price'] as num).toDouble();Handling a FormatException
jsonDecode throws FormatException for invalid text. Catch it where you can add context, because the default message does not say which request failed.
import 'dart:convert';
dynamic safeDecode(String source, {required String context}) {
try {
return jsonDecode(source);
} on FormatException catch (e) {
throw FormatException('Invalid JSON from $context: ${e.message}', source);
}
}Type-cast failures are different. They throw TypeError, which is an Error, not an Exception. A plain on Exception clause will not catch them. Later chapters return to this when they cover checked mode and structured error handling.
Where this approach hurts
The code in this chapter is correct, but it has three weaknesses that motivate the rest of the tutorial.
- Keys are strings. A typo such as
map['nmae']compiles and returnsnull. Nothing checks it until run time. - Casts are repeated. Every field needs its own
as, and every nullable field needs the right?. Adding a field means editing parsing code, encoding code, and the class. - Nested data multiplies the work. Each nested object and list needs its own conversion loop, and each loop has the same cast pitfalls.
None of these are bugs in dart:convert. The library is deliberately low-level. It gives you a faithful Map and List view of the document and leaves typing to you. The next chapters show the cost of doing that by hand and then replace it with generated code that still calls jsonDecode and jsonEncode underneath.
Summary of the working model
jsonDecodereturnsdynamic. Objects becomeMap<String, dynamic>, arrays becomeList<dynamic>.- Numbers become
intordoubledepending on how they are written. Read uncertain numeric fields asnum. jsonEncodewrites only the basic types. Anything else must providetoJson().- Bytes must be decoded as UTF-8 before or while parsing.
- A
FormatExceptionmeans invalid text. ATypeErrormeans valid JSON with an unexpected shape.
Exercise
A server returns {"scores": [10, 20, 30], "average": 20}. Your code does final scores = map['scores'] as List<int>; and final avg = map['average'] as double;. Both lines throw. Why, and how do you fix each line?
Show answer
The first fails because jsonDecode produces a List<dynamic>, and a List<dynamic> cannot be cast to List<int>. Use (map['scores'] as List<dynamic>).cast<int>() or .map((e) => e as int).toList(). The second fails because 20 has no fraction, so the decoder returns an int, and an int cannot be cast to double. Use (map['average'] as num).toDouble().
Exercise
You call jsonEncode({'created': DateTime(2026, 11, 28)}) and get a JsonUnsupportedObjectError. Why does this happen, and what is one way to fix it?
Show answer
jsonEncode only handles maps, lists, strings, numbers, booleans, and null, and it falls back to calling toJson() on other objects. DateTime has no toJson() that the encoder uses, so it raises the error. Convert the value first, for example {'created': DateTime(2026, 11, 28).toIso8601String()}, or wrap it in a class that defines toJson().