Sub topic 8
Nested objects and lists
This chapter assumes you have annotated a model with @JsonSerializable, run build_runner, and used @JsonKey and class-level options such as fieldRename. It covers what the generator does when a field is another model, a list of models, or a map of models. It also covers the one option that most often causes confusion, explicitToJson.
How the generator treats nested types
Real API responses are rarely flat. A customer has an address, and an address is an object. A customer also has orders, and orders are a list of objects. json_serializable handles this by delegation. When it meets a field whose type is another class, it calls that class's fromJson and toJson.
For that to work, the nested class must meet two requirements:
- It must provide a
fromJsonfactory that takes aMap<String, dynamic>, or a constructor with that name. - It must provide a
toJson()method that returns aMap<String, dynamic>.
Annotating the nested class with @JsonSerializable and following the usual pattern satisfies both. The generator does not create nested classes for you, and it does not look at the nested class's fields. It only calls the two methods.
A complete example
Save this as customer.dart. All three classes share one generated file, customer.g.dart, because they live in the same library.
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
part 'customer.g.dart';
@JsonSerializable(explicitToJson: true)
class Customer {
const Customer({
required this.id,
required this.address,
required this.orders,
this.tags = const [],
});
factory Customer.fromJson(Map<String, dynamic> json) =>
_$CustomerFromJson(json);
final int id;
final Address address;
final List<Order> orders;
@JsonKey(defaultValue: <String>[])
final List<String> tags;
Map<String, dynamic> toJson() => _$CustomerToJson(this);
}
@JsonSerializable()
class Address {
const Address({required this.street, required this.city});
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
final String street;
final String city;
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
@JsonSerializable()
class Order {
const Order({required this.id, required this.skus});
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
final int id;
final List<String> skus;
Map<String, dynamic> toJson() => _$OrderToJson(this);
}
void main() {
const source = '''
{
"id": 7,
"address": {"street": "1 Main St", "city": "Leeds"},
"orders": [
{"id": 100, "skus": ["A-1", "B-2"]},
{"id": 101, "skus": []}
]
}
''';
final customer = Customer.fromJson(
jsonDecode(source) as Map<String, dynamic>,
);
print(customer.address.city); // Leeds
print(customer.orders.length); // 2
print(customer.tags); // [] because "tags" is absent
print(jsonEncode(customer.toJson()));
}Run dart run build_runner build --delete-conflicting-outputs, then dart run customer.dart. The code imports no Flutter libraries, so it runs as plain Dart. In a Flutter project you would normally place it under lib/ and call it from your app code.
What the generated code does
You never edit customer.g.dart, but reading it explains most runtime errors. The decoding side for orders looks roughly like this:
orders: (json['orders'] as List<dynamic>)
.map((e) => Order.fromJson(e as Map<String, dynamic>))
.toList(),This code performs three steps, and each can fail:
json['orders'] as List<dynamic>fails if the key is missing or the value is not an array.e as Map<String, dynamic>fails if any element is not an object, for example anullor a bare number.Order.fromJsonruns its own casts on the nested fields.
For List<String>, the generated .map casts each element with e as String. That cast matters because jsonDecode returns List<dynamic>. You cannot assign it directly to a List<String> field.
The generator supports the same shape for other collections:
| Field type | Behavior |
|---|---|
| `Address` | Calls `Address.fromJson` on the nested map. |
| `List<Order>` | Maps each element through `Order.fromJson`. |
| `List<Order>?` | Returns `null` when the key is absent or `null`. |
| `List<Order?>` | Allows `null` elements inside the array. |
| `Map<String, Order>` | Maps each value through `Order.fromJson`. Keys must be strings. |
| `List<List<int>>` | Handles nested lists recursively. |
| `Map<String, dynamic>` | Passes the map through untouched. |
Nullability and missing lists
APIs often omit an empty list or send null instead. You have three ways to handle it, and each puts a different promise in your model:
- Make the field nullable (
List<Order>? orders). Every consumer must then handlenull. - Keep it non-nullable and add
@JsonKey(defaultValue: <Order>[]). A missing ornullvalue becomes an empty list, and callers never seenull. - Keep it non-nullable and
required. A missing key then throws during decoding.
The second option usually gives the cleanest widget code. The third is right when a missing list means the response is broken and you want to find out immediately. Pair defaultValue with a matching constructor default, as Customer.tags does above. Direct construction in tests then behaves the same as decoding.
Why explicitToJson matters
By default, the generated toJson does not call toJson on nested objects. It puts the nested instance into the map. For Customer without the option, the output is conceptually this:
// Generated without explicitToJson:
<String, dynamic>{
'id': instance.id,
'address': instance.address, // an Address object, not a Map
'orders': instance.orders, // a List<Order>, not a list of Maps
'tags': instance.tags,
}With explicitToJson: true, the generator writes instance.address.toJson() and instance.orders.map((e) => e.toJson()).toList().
The default hides the problem in the common path. jsonEncode calls toJson() on any object it cannot encode, so jsonEncode(customer.toJson()) produces correct text either way. The problem appears when you use the map itself:
final map = customer.toJson();
// Without explicitToJson this throws a TypeError at runtime:
final city = (map['address'] as Map<String, dynamic>)['city'];Any code that reads the map directly sees the difference. That includes equality checks in tests, writing the map to a database that expects plain values, and sending it through a platform channel. A decoder that does not call toJson fails the same way. The failure message is the other symptom:
Converting object to an encodable object failed: Instance of 'Address'This message means a nested class has no toJson method. The error is different from the explicitToJson case, where the method exists but is not called.
Turning it on everywhere
Setting the option on every class is easy to forget. You can set it once for the package in build.yaml, next to pubspec.yaml:
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: trueAnnotation arguments override these defaults. After you change build.yaml, run the build again so the generated files pick it up.
Common errors
type 'Null' is not a subtype of type 'List<dynamic>' in type cast. The key is missing ornull, and the field is non-nullable with no default. Make the field nullable or adddefaultValue.type '_Map<String, dynamic>' is not a subtype...pointing at a nested class. The JSON shape differs from your model, for example an object where you declared a list. Print the raw JSON and compare it with the model field by field.- Nested values come back as
Instance of 'X'in a test.toJsonwas used withoutexplicitToJson. Enable the option. - The build succeeds but nested fields are missing from
toJson. The field has@JsonKey(includeToJson: false)or the nested class was not annotated. Check both. - A build error saying the nested type does not support
toJson. The nested class has notoJsonmethod the generator can find. Add the method or aJsonConverter, which the custom converters chapter covers.
Testing the nested shape
Compare the map, not only the encoded string. With explicitToJson on, this test passes. It would fail without the option.
import 'package:flutter_test/flutter_test.dart';
import 'customer.dart';
void main() {
test('toJson returns plain maps and lists', () {
const customer = Customer(
id: 7,
address: Address(street: '1 Main St', city: 'Leeds'),
orders: [Order(id: 100, skus: ['A-1'])],
);
final map = customer.toJson();
expect(map['address'], isA<Map<String, dynamic>>());
expect(map['orders'], everyElement(isA<Map<String, dynamic>>()));
expect((map['address'] as Map)['city'], 'Leeds');
});
}Exercise
A model has final List<Order> orders; and @JsonSerializable() with no options. jsonEncode(model.toJson()) produces correct JSON, but a test that calls model.toJson()['orders'] and expects a List<Map<String, dynamic>> fails. Why, and what are two ways to fix it?
Show answer
Without explicitToJson, the generated toJson stores the List<Order> itself in the map. jsonEncode works because it calls toJson() on each Order while encoding, but the map holds Order instances. Fix it by setting @JsonSerializable(explicitToJson: true) on the class, or by setting explicit_to_json: true for the whole package in build.yaml and rebuilding.
Exercise
An API returns "orders": null for customers with no orders, and sometimes omits the key. You want Customer.orders to be a non-nullable List<Order> that is empty in both cases. What do you write, and what input would still throw?
Show answer
Annotate the field with @JsonKey(defaultValue: <Order>[]) and give the constructor parameter this.orders = const []. Both null and a missing key then produce an empty list. Input such as "orders": "none" or "orders": [1, 2] would still throw a cast error, because defaultValue only covers missing and null values.