pub struct Json<T>(pub T);
json
only.Expand description
JSON Extractor / Response.
When used as an extractor, it can deserialize request bodies into some type that
implements serde::Deserialize
. If the request body cannot be parsed, or it does not contain
the Content-Type: application/json
header, it will reject the request and return a
400 Bad Request
response.
Extractor example
use axum::{
extract,
routing::post,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
email: String,
password: String,
}
async fn create_user(extract::Json(payload): extract::Json<CreateUser>) {
// payload is a `CreateUser`
}
let app = Router::new().route("/users", post(create_user));
When used as a response, it can serialize any type that implements serde::Serialize
to
JSON
, and will automatically set Content-Type: application/json
header.
Response example
use axum::{
extract::Path,
routing::get,
Router,
Json,
};
use serde::Serialize;
use uuid::Uuid;
#[derive(Serialize)]
struct User {
id: Uuid,
username: String,
}
async fn get_user(Path(user_id) : Path<Uuid>) -> Json<User> {
let user = find_user(user_id).await;
Json(user)
}
async fn find_user(user_id: Uuid) -> User {
// ...
}
let app = Router::new().route("/users/:id", get(get_user));
Tuple Fields
0: T
Trait Implementations
type Rejection = JsonRejection
type Rejection = JsonRejection
If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response. Read more
fn from_request<'life0, 'async_trait>(
req: &'life0 mut RequestParts<B>
) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>> where
'life0: 'async_trait,
Self: 'async_trait,
fn from_request<'life0, 'async_trait>(
req: &'life0 mut RequestParts<B>
) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>> where
'life0: 'async_trait,
Self: 'async_trait,
Perform the extraction.
Create a response.
Auto Trait Implementations
impl<T> RefUnwindSafe for Json<T> where
T: RefUnwindSafe,
impl<T> UnwindSafe for Json<T> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
Create a new Policy
that returns Action::Follow
only if self
and other
return
Action::Follow
. Read more
pub fn vzip(self) -> V
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more