serde Basics
9 examples to get you started with serde - 6 basic and 3 intermediate.
Busca en todas las páginas de la documentación
9 examples to get you started with serde - 6 basic and 3 intermediate.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"serde_json, toml, etc.) per wire format.Turn a struct into JSON.
use serde::Serialize;
#[derive(Serialize)]
struct User { id: u64, name: String }
let u = User { id: 1, name: "Ada".into() };
let json = serde_json::to_string(&u).unwrap();#[derive(Serialize)] generates the trait impl.to_string allocates; to_vec for bytes.Related: JSON with serde_json - parsing and
Value
Parse JSON into a struct.
use serde::Deserialize;
#[derive(Deserialize)]
struct Point { x: i32, y: i32 }
let p: Point = serde_json::from_str(r#"{"x":1,"y":2}"#).unwrap();Option or default.String for untrusted input.Round-trip types need both derives.
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Config { debug: bool }Debug for test assertions.Clone when storing configs in state.Serialize lists and maps.
#[derive(Serialize)]
struct Batch { items: Vec<String> }
let json = serde_json::to_string(&Batch { items: vec!["a".into()] }).unwrap();Vec, HashMap, BTreeMap work out of the box.[] or {}.Optional JSON keys map to Option.
#[derive(Deserialize)]
struct Profile { bio: Option<String> }None.null in JSON also maps to None for Option<T>.Simple tagged enums.
#[derive(Serialize, Deserialize)]
enum Status { Active, Inactive }Related: Enums & Tagging - representation options
Match foreign API camelCase.
#[derive(Deserialize)]
struct ApiUser {
#[serde(rename = "userId")]
id: u64,
}rename_all = "camelCase" on the struct for all fields.Related: Customizing Serialization - more attributes
Fill missing fields with defaults.
#[derive(Deserialize)]
struct Settings {
#[serde(default)]
retries: u32,
}Default::default() for the field type.Serde supports generics with bounds.
#[derive(Serialize, Deserialize)]
struct Page<T> { items: Vec<T> }
#[derive(Serialize, Deserialize)]
struct Item { id: u64 }T must implement Serialize / Deserialize.Vec<T>, Option<T>, nested generics.Related: Custom (De)serialization - manual impls
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026