Sub topic 13
Generic response wrappers
Assume you already know Dart generics, null safety, and the basic json_serializable workflow. This chapter shows how to serialize a class whose field type is a type parameter, such as ApiResponse<T>.
Why generic wrappers need extra information
A common API response wraps different payload types in the same structure:
{
"data": {
"id": 7,
"name": "Ada"
},
"message": null
}The wrapper is always the same, but data might be a User, Order, or list of users. Dart can represent this with ApiResponse<T>:
ApiResponse<User>
ApiResponse<Order>
ApiResponse<List<User>>The JSON decoder cannot determine what T means by itself. A JSON object does not contain Dart's generic type information. You must provide a function that converts the raw data value into T.
flowchart TD
A[JSON response] --> B[ApiResponse.fromJson]
B --> C[Read data as Object?]
C --> D[Provided converter]
D --> E[Concrete value such as User]Enable generic argument factories
Set genericArgumentFactories: true on the wrapper. This tells json_serializable to add converter functions to the generated methods.
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
part 'api_response.g.dart';
@JsonSerializable()
class User {
const User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson(json);
final int id;
final String name;
Map<String, dynamic> toJson() => _$UserToJson(this);
}
@JsonSerializable(genericArgumentFactories: true)
class ApiResponse<T> {
const ApiResponse({required this.data, this.message});
factory ApiResponse.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
) =>
_$ApiResponseFromJson(json, fromJsonT);
final T data;
final String? message;
Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
_$ApiResponseToJson(this, toJsonT);
}
ApiResponse<User> parseUserResponse(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
return ApiResponse<User>.fromJson(
json,
(value) => User.fromJson(value as Map<String, dynamic>),
);
}The fromJsonT function receives the raw JSON value and creates a T. The toJsonT function performs the reverse operation when encoding a response.
Generate the supporting file after saving the model:
dart run build_runner build --delete-conflicting-outputsWrapping lists and other types
The converter can create any type, not only one model class. For a response containing a list of users, convert each list item separately:
ApiResponse<List<User>> parseUsersResponse(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
return ApiResponse<List<User>>.fromJson(
json,
(value) => (value as List<dynamic>)
.map((item) => User.fromJson(item as Map<String, dynamic>))
.toList(),
);
}The cast at the JSON boundary is important. It documents the shape you expect and causes malformed data to fail near the source.
Common mistakes
- Omitting
genericArgumentFactories: true, which prevents generated methods from accepting converters. - Calling
ApiResponse.fromJsonwithout specifying the type argument when Dart cannot inferT. - Passing
User.fromJsondirectly when the callback receivesObject?; wrap it with a cast. - Forgetting to pass a converter to
toJson. - Using one converter for every endpoint even when different endpoints return different shapes.
Exercise
What converter should you pass to ApiResponse<User>.fromJson when the data JSON value is an object?
Show answer
Pass a function such as (value) => User.fromJson(value as Map<String, dynamic>).