Serde JSON
Serde is Rust's serialisation framework. #[derive(Serialize, Deserialize)] on a struct, plus serde_json, turns JSON into typed values and back.
Detailed Explanation
serde is the traits (Serialize, Deserialize) and the derive macros. serde_json is one format. The same struct can also talk to toml, yaml, bincode, or a custom format. You derive once. You pick the format crate at the edge.
#[derive(Deserialize)] struct User { id: u64, name: String } plus serde_json::from_str::<User>(body) rejects missing fields by default, rejects unknown types, and leaves you with a User or an error. #[serde(default)], #[serde(rename = "userName")], #[serde(skip_serializing_if = "Option::is_none")] are the attributes you will actually use. #[serde(flatten)] inlines another struct's fields.
Unknown fields are ignored by default in some configurations and can be denied with #[serde(deny_unknown_fields)] when you want a strict API. Optionality is Option<T> or #[serde(default)]. A missing Option becomes None. A missing String is an error unless you default it.
Do not unwrap from_str on a network body. The error is a 400. Do not serialise a type that contains a secret without skip. Do not use Value (untyped JSON) as your domain model; it postpones every typo to runtime. Value is for pass-through blobs and partially unknown documents.
When you derive Serde: any struct that crosses a wire or a disk format. When you write a manual impl: a type that is not a struct-shaped record (an enum with a custom external tag, a HashMap with non-string keys). When you skip Serde: a type that never leaves the process.
Enums need an explicit tag style (externally tagged is the default, #[serde(tag = "type")] is adjacently tagged, untagged is last-match-wins). An untagged enum that cannot distinguish its variants will silently pick the wrong one. Write a test that round-trips each variant and one that rejects an ambiguous document.
Code Examples
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
id: u64,
name: String,
}
fn main() {
let raw = r#"{"id":17,"name":"ada"}"#;
let user: User = serde_json::from_str(raw).unwrap();
println!("{} {}", user.id, user.name); // prints: 17 ada
println!("{}", serde_json::to_string(&user).unwrap()); // prints: {"id":17,"name":"ada"}
}Common Gotchas
A missing required field is an error
`name` as `String` will not default to empty. Use `Option` or `#[serde(default)]` if absence is allowed.
`unwrap` on `from_str` in a handler is a panic on bad JSON
Map the error to 400.
`rename` is how you speak camelCase
Rust fields stay snake_case. The wire name is an attribute, not a different struct.
`Value` is untyped
A typo in a key becomes a runtime miss. Parse into a struct at the boundary.