json<T> method
Processes the response as JSON with optional transformation.
This method sends the request, validates the response, and parses the response body as JSON. An optional transformation function can be provided to convert the parsed JSON to the desired type.
fn Optional function to transform the parsed JSON map.
Returns a Future that resolves to the transformed result or void.
Throws ServiceError if the request fails or returns an error status.
Example
// Simple JSON parsing
await request('/api/users').get().json();
// With transformation
final users = await request('/api/users')
.get()
.json<List>((json) => json['users']);
Implementation
Future<T> json<T>([T Function(Map<String, dynamic>)? fn]) async {
final response = await _request.send();
await _checkResponse(response);
final bodyBytes = await response.stream.toBytes();
if (fn != null) {
final json = jsonDecode(utf8.decode(bodyBytes)) as Map<String, dynamic>;
return fn(json);
}
return Future.value() as T;
}