expression

Axum: deserialize a JSON request

A JSON extractor turns a supported JSON request body into a typed Rust value. A correct content type and valid field types are required. A successfully decoded string still needs business validation before storage. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): hello Mina Common mistake: Omitting the content type or equating deserialization with business validation.

Formal Syntax & Structure

rust syntaxrust
Json(input): Json<Input>

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{Json, routing::post};    #[derive(serde::Deserialize)]    struct Input { name: String }    async fn create(Json(input): Json<Input>) -> String { format!("hello {}", input.name) }    let app = Router::new().route("/greet", post(create));    let r = app.oneshot(Request::builder().method("POST").uri("/greet").header("content-type", "application/json").body(Body::from(r#"{"name":"Mina"}"#)).unwrap()).await.unwrap();    println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 128).await.unwrap()).unwrap());}
Rust Reference