Json response type serializes data to JSON and automatically sets the Content-Type: application/json header.
Basic usage
Return any type that implementsserde::Serialize:
How it works
IntoResponse implementation
TheJson type implements IntoResponse by serializing the inner value using serde_json:
axum/src/json.rs:197-232.
Serialization behavior
The serialization process:- Creates a
BytesMutbuffer with 128-byte initial capacity - Serializes the value using
serde_json::to_writer - On success: Returns response with
Content-Type: application/jsonheader - On failure: Returns
500 Internal Server Errorwith error message as plain text
Error handling
If serialization fails (e.g., map with non-string keys), a 500 status code is returned with the error message:ForceStatusCode:
Response fields
header
Automatically set to
application/jsonbytes
The serialized JSON bytes
Common patterns
Returning JSON with custom status
Returning JSON arrays
See also
- Extract JSON request bodies using the Json extractor
- IntoResponse trait for custom response types