json method
Writes a JSON response and closes the connection.
If data is already a string, it is written as-is. Otherwise the value is
encoded with jsonEncode.
The response is sent with 200 OK, a JSON content type, content length,
cache headers, and persistent connection enabled.
Example:
return request.json({
'message': 'User created',
'user': user.toJson(),
});
Implementation
Future<HttpResponse> json([dynamic data]) async {
final String body = (data is String) ? data : jsonEncode(data);
response.headers.contentType = _jsonType;
response.headers.set(HttpHeaders.cacheControlHeader, 'public, max-age=300');
response.headers.contentLength = utf8.encode(body).length;
response.headers.set(HttpHeaders.connectionHeader, 'keep-alive');
response.persistentConnection = true;
return response
..statusCode = HttpStatus.ok
..write(body)
..close();
}