Converters
Converters are used to apply transformations on request and/or response bodies, for example, transforming a Dart object to a Map<String, dynamic> or vice versa.
Both converter and errorConverter are called before request and response interceptors.
1
final chopper = ChopperClient(
2
converter: JsonConverter(),
3
errorConverter: JsonConverter()
4
);
Copied!
The errorConverter is called only on error responses (statusCode < 200 || statusCode >= 300).

The built-in JSON converter

Chopper provides a JsonConverter that is able to encode data to JSON and decode JSON strings. It will also apply the correct header to the request (application/json).
However, if content type header is modified (for example by using @Post(headers: {'content-type': '...'})), JsonConverter won't add the header and it won't call json.encode if content type is not JSON.
JsonConverter itself won't convert a Dart object into a Map<String, dynamic> or a List, but it will convert a Map<String, dynamic> into a JSON string.

Implementing custom converters

You can implement custom converters by implementing the Converter class.
1
class MyConverter implements Converter {
2
@override
3
Response<BodyType> convertResponse<BodyType, InnerType>(Response response) {
4
var body = response.body;
5
// Convert body to BodyType however you like
6
response.copyWith<BodyType>(body: body);
7
}
8
โ€‹
9
@override
10
Request convertRequest(Request request) {
11
var body = request.body;
12
// Convert body to String however you like
13
return request.copyWith(body: body);
14
}
15
}
Copied!
BodyTypeis the expected type of the response body (e.g., String or CustomObject).
If BodyType is a List or a BuiltList, InnerType is the type of the generic parameter (e.g., convertResponse<List<CustomObject>, CustomObject>(response)).

Using different converters for specific endpoints

If you want to apply specific converters only to a single endpoint, you can do so by using the @FactoryConverter annotation:
1
@ChopperApi(baseUrl: "/todos")
2
abstract class TodosListService extends ChopperService {
3
โ€‹
4
@FactoryConverter(
5
request: FormUrlEncodedConverter.requestFactory,
6
response: convertResponse,
7
)
8
@Post(path: '/')
9
Future<Response> post(@Field() String foo, @Field() int bar);
10
โ€‹
11
}
12
โ€‹
13
Response<T> convertResponse<T>(Response res) =>
14
JsonConverter().convertResponse(res);
Copied!