Data crossing the wire needs a contract.
Separate transport formats from valid domain values.
01 Understand the contract
Serialization converts typed data into a transport representation; deserialization performs the reverse. Serde derives these operations for compatible types, with serde_json supplying JSON encoding. A syntactically valid JSON document can still violate your domain rules. Deserialize into an input type, validate length, range, and required relationships, then construct a domain value. The Axum task API cookbook demonstrates this full path with JSON input and status codes. Never build JSON or SQL by concatenating untrusted text.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
#[derive(Debug, PartialEq)]
struct Title(String);
impl Title {
fn parse(raw: &str) -> Result<Self, &'static str> {
let value = raw.trim();
if value.is_empty() || value.chars().count() > 80 {
Err("title must contain 1–80 characters")
} else {
Ok(Self(value.to_owned()))
}
}
}
fn main() {
let title = Title::parse(" Build ").unwrap();
println!("{}", title.0);
assert!(Title::parse(" ").is_err());
}Build
- 1
Parsing transport text and validating domain meaning are separate steps.
- 2
Trim defines the accepted normalization policy.
- 3
The owned Title can be passed beyond the input buffer’s lifetime.
cargo run -p lesson_serialization03 Mind the boundary
04 Your next build
Validate a username of 3–16 ASCII alphanumeric characters, rejecting spaces.
Reveal one possible solution +
fn valid(s: &str) -> bool {
(3..=16).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn main() {
assert!(valid("navan7"));
assert!(!valid("ab"));
assert!(!valid("a b"));
assert!(!valid("ééé"));
}05 Check your reasoning
Does successful JSON deserialization guarantee valid business data?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.