expression

Axum: serialize a JSON response

Return a serializable value inside Json to generate a JSON response. A status tuple lets a handler express creation or another outcome. The example parses the returned JSON instead of depending on formatting. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 201 application/json 8 Common mistake: Comparing serialized key order instead of decoded field values.

Formal Syntax & Structure

rust syntaxrust
Json(output); (StatusCode, Json(output))

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::Serialize, serde::Deserialize)]    struct Item { id: u32 }    async fn create() -> (StatusCode, Json<Item>) { (StatusCode::CREATED, Json(Item { id: 8 })) }    let app = Router::new().route("/items", post(create));    let r = app.oneshot(Request::builder().method("POST").uri("/items").body(Body::empty()).unwrap()).await.unwrap();    println!("{}", r.status().as_u16());    println!("{}", r.headers()["content-type"].to_str().unwrap());    let item: Item = serde_json::from_slice(&to_bytes(r.into_body(), 128).await.unwrap()).unwrap();    println!("{}", item.id);}
Rust Reference