Sub topic 8
Nested Objects and Lists
This chapter assumes you know Dart classes, constructors, null safety, lists, and basic REST responses. You will learn how json_serializable converts nested JSON objects and lists into typed Dart objects.
Model nested data
Suppose an order response contains line items:
{
"order_id": 42,
"items": [
{"sku": "BOOK-1", "quantity": 2},
{"sku": "PEN-4", "quantity": 1}
]
}The items value is a JSON array. Each array element is a JSON object. Model both levels with Dart classes:
import 'package:json_annotation/json_annotation.dart';
part 'order.g.dart';
@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake)
class Order {
const Order({
required this.orderId,
required this.items,
});
factory Order.fromJson(Map<String, dynamic> json) =>
_$OrderFromJson(json);
final int orderId;
final List<LineItem> items;
Map<String, dynamic> toJson() => _$OrderToJson(this);
}
@JsonSerializable()
class LineItem {
const LineItem({
required this.sku,
required this.quantity,
});
factory LineItem.fromJson(Map<String, dynamic> json) =>
_$LineItemFromJson(json);
final String sku;
final int quantity;
Map<String, dynamic> toJson() => _$LineItemToJson(this);
}List<LineItem> tells the generator that every element should become a LineItem. During deserialization, generated code calls LineItem.fromJson for each object. During serialization, it calls toJson for each LineItem.
explicitToJson: true makes this nested conversion explicit in generated code. Use it when a class contains other serializable objects. It also makes the generated behavior easier to inspect and maintain.
Generate and use the models
Run the generator after adding or changing annotations:
dart run build_runner build --delete-conflicting-outputsThe command creates order.g.dart. Do not edit that file manually. Edit order.dart, then run the generator again.
You can now decode a response:
import 'dart:convert';
Order parseOrder(String responseBody) {
final decoded = jsonDecode(responseBody) as Map<String, dynamic>;
return Order.fromJson(decoded);
}
String encodeOrder(Order order) {
return jsonEncode(order.toJson());
}The generated code checks the order_id key because the class uses FieldRename.snake. It also maps the JSON items array into List<LineItem>.
| JSON value | Dart type | Conversion |
|---|---|---|
| Object | A model class | `Model.fromJson` |
| Array of objects | `List<Model>` | Convert every element |
| Array of strings | `List<String>` | Convert each scalar value |
Common errors
A nested class must also be annotated with @JsonSerializable(). Without that annotation and its generated methods, the generator cannot reliably construct the nested object.
The JSON shape must match the Dart type. If items is sometimes null, declare it as List<LineItem>? or provide a default. If it is missing but should mean an empty list, use a @JsonKey(defaultValue: []) configuration carefully, because mutable default values need deliberate handling.
A list of objects is different from a single object. Use List<LineItem> for an array and LineItem for one object. Casting the wrong shape produces a runtime error while decoding.
Conversion flow
Exercise
What Dart type should represent a JSON array containing objects with sku and quantity fields?
Show answer
Use List<LineItem>, where LineItem is an annotated class with fromJson and toJson methods.