0Pricing
Learn Rust Coding · Lesson

JSON and State

Shared state and serialization.

Returning JSON

Axum makes JSON responses easy. Wrap any Serialize type in Json and it sets the content type and serializes the body.

use axum::Json;
use serde::Serialize;

#[derive(Serialize)]
struct User { id: u32, name: String }

async fn get_user() -> Json<User> {
    Json(User { id: 1, name: "Alice".into() })
}

Serializing collections

A Vec of serializable items becomes a JSON array. No extra work needed.

use axum::Json;
use serde::Serialize;

#[derive(Serialize)]
struct Item { id: u32 }

async fn list() -> Json<Vec<Item>> {
    Json(vec![Item { id: 1 }, Item { id: 2 }])
}

All lessons in this course

  1. Axum Routing
  2. Extractors
  3. JSON and State
  4. Middleware
← Back to Learn Rust Coding