Sub topic 7
Container-level attributes
This chapter assumes you can derive Serialize and Deserialize and round-trip a struct through serde_json. It also assumes you know the field attributes rename and default.
What "container" means
serde calls the struct or enum that carries the derive the container. A container attribute sits above the type and applies to everything inside it. It uses the same #[serde(...)] syntax as field attributes, and you can combine several in one list.
Container attributes avoid repetition. Without rename_all, you would write #[serde(rename = "...")] on every field.
rename_all
rename_all changes the case convention of every field name, or of every variant name when the container is an enum. Rust uses snake_case for fields, but many JSON APIs use camelCase.
| Value | Example result |
|---|---|
| `"lowercase"` | `username` |
| `"UPPERCASE"` | `USERNAME` |
| `"PascalCase"` | `UserName` |
| `"camelCase"` | `userName` |
| `"snake_case"` | `user_name` |
| `"SCREAMING_SNAKE_CASE"` | `USER_NAME` |
| `"kebab-case"` | `user-name` |
| `"SCREAMING-KEBAB-CASE"` | `USER-NAME` |
A field-level rename overrides rename_all for that one field.
deny_unknown_fields
By default, serde ignores JSON keys that the struct does not declare. That is lenient, but it hides typos in configuration files. deny_unknown_fields turns an unexpected key into an error.
Container-level default
Placing #[serde(default)] on the container fills any missing field from the type's Default implementation. The type must implement Default. This differs from field-level default, which uses the default of that field's type. At container level you can pick your own values, such as retry_count: 3.
Putting them together
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields, default)]
struct Settings {
user_name: String,
retry_count: u32,
use_tls: bool,
}
impl Default for Settings {
fn default() -> Self {
Settings {
user_name: "guest".to_string(),
retry_count: 3,
use_tls: true,
}
}
}
fn main() -> Result<(), serde_json::Error> {
let settings: Settings = serde_json::from_str(r#"{"retryCount":5}"#)?;
println!("{settings:?}");
println!("{}", serde_json::to_string(&settings)?);
let err = serde_json::from_str::<Settings>(r#"{"retrycount":5}"#).unwrap_err();
println!("{err}");
Ok(())
}The first line prints Settings { user_name: "guest", retry_count: 5, use_tls: true }. The missing fields came from Default. The second line prints {"userName":"guest","retryCount":5,"useTls":true}, so the names are camelCase on output.
The third line prints an error that starts with `unknown field retrycount, expected one of userName, retryCount, useTls `. The key is misspelled, so serde rejects it and lists the valid names.
Renaming only one direction
rename_all applies to both serializing and deserializing. To rename in one direction only, use the longer form:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
struct Account {
account_id: u32,
}
fn main() -> Result<(), serde_json::Error> {
let account: Account = serde_json::from_str(r#"{"account_id":7}"#)?;
println!("{}", serde_json::to_string(&account)?); // {"accountId":7}
Ok(())
}This helps when you read one naming style and must write another.
Common errors
- Adding container
defaultwithout implementingDefaultgives a compile error. - Expecting
rename_allto change a field that already hasrename. The explicit name wins. - Using
deny_unknown_fieldson a type that must accept newer versions of the data. Old readers will then fail on new keys.
Exercise
A struct has fields first_name and last_name. You add #[serde(rename_all = "SCREAMING_SNAKE_CASE")] and put #[serde(rename = "surname")] on last_name. What JSON keys does serialization produce?
Show answer
FIRST_NAME and surname. The container attribute renames first_name, but the field-level rename overrides it for last_name.