Sub topic 7
Container-level attributes
A container is the struct or enum that a derive is attached to. Container attributes go on that type and apply to all of it. This chapter covers the ones you will use most: rename_all, deny_unknown_fields, default, transparent, and the conversion attributes from, into, and try_from.
This chapter assumes you can derive Serialize and Deserialize, use serde_json, and read a Result. The examples use the same serde (with the derive feature) and serde_json dependencies as the earlier chapters.
Where container attributes go
A container attribute sits in a #[serde(...)] list directly above the type. You can combine several in one list, separated by commas.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Settings {
user_name: String,
retry_count: u32,
}Field attributes sit on individual fields. When both levels say something about the same name, the field wins.
Renaming everything with rename_all
rename_all converts every field name, or every variant name for an enum, to one naming convention. Rust fields are normally snake_case and variants are PascalCase. The attribute converts from those to the target style.
| Rule | Field `retry_count` becomes |
|---|---|
| `lowercase` | `retry_count` |
| `UPPERCASE` | `RETRY_COUNT` |
| `PascalCase` | `RetryCount` |
| `camelCase` | `retryCount` |
| `snake_case` | `retry_count` |
| `SCREAMING_SNAKE_CASE` | `RETRY_COUNT` |
| `kebab-case` | `retry-count` |
| `SCREAMING-KEBAB-CASE` | `RETRY-COUNT` |
On an enum, rename_all changes the variant names:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum Level {
Debug,
Warn,
ErrorLevel,
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Level::ErrorLevel)?); // "ERROR_LEVEL"
let level: Level = serde_json::from_str(r#""WARN""#)?;
println!("{level:?}"); // Warn
Ok(())
}Two details cause surprises:
- On an enum,
rename_alldoes not touch the fields inside struct-like variants. Userename_all_fieldsfor that. It needs serde 1.0.186 or later. - To use different styles for each direction, pass a pair:
#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))].
A field-level #[serde(rename = "...")] always overrides rename_all for that one field.
Rejecting unknown keys with deny_unknown_fields
By default, deserialization ignores keys that the struct does not have. That is forgiving, but it hides typos. A config file with "retrycount": 5 silently leaves the real field at its default.
deny_unknown_fields turns that into an error:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Settings {
user_name: String,
retry_count: u32,
}
fn main() {
let ok = r#"{"userName":"ada","retryCount":3}"#;
println!("{:?}", serde_json::from_str::<Settings>(ok));
let bad = r#"{"userName":"ada","retryCount":3,"extra":1}"#;
match serde_json::from_str::<Settings>(bad) {
Ok(s) => println!("{s:?}"),
// unknown field `extra`, expected `userName` or `retryCount` at line 1 column ...
Err(e) => println!("{e}"),
}
}The error names the offending key and lists the keys it expected, using the renamed spellings. The message ends with the line and column where parsing stopped.
Use this attribute for input you control and want to validate strictly, such as config files. Avoid it for input from a service that may add fields later. A strict reader breaks when the producer adds a field, even though old code could safely ignore it.
Filling gaps with a container-level default
You have seen #[serde(default)] on a single field. On a container it means: for every field missing from the input, take the value from the struct's own Default implementation. The type must implement Default.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(default)]
struct Server {
host: String,
port: u16,
verbose: bool,
}
impl Default for Server {
fn default() -> Self {
Server {
host: "localhost".to_string(),
port: 8080,
verbose: false,
}
}
}
fn main() -> Result<(), serde_json::Error> {
let server: Server = serde_json::from_str(r#"{"port":9000}"#)?;
println!("{server:?}"); // Server { host: "localhost", port: 9000, verbose: false }
Ok(())
}The advantage over per-field defaults is that you describe the defaults once, in ordinary Rust, and the same Default works outside serde. You can also write #[serde(default = "path::to::fn")]. The function must return the whole struct.
Defaults apply only when a key is absent. A key that is present with the wrong type is still an error.
Treating a wrapper as its inner value with transparent
A newtype is a one-field struct that exists to give a value its own type. By default, serde serializes a newtype struct as its inner value. Named-field structs with a single field are serialized as objects. transparent makes any one-field struct serialize as the field alone:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
struct UserId(u64);
#[derive(Debug, Serialize, Deserialize)]
struct Account {
id: UserId,
name: String,
}
fn main() -> Result<(), serde_json::Error> {
let account = Account { id: UserId(7), name: "Ada".to_string() };
let json = serde_json::to_string(&account)?;
println!("{json}"); // {"id":7,"name":"Ada"}
let back: Account = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}transparent requires exactly one field that serde handles. Any other fields must be skipped with #[serde(skip)], which makes PhantomData markers possible. It is most useful for named-field wrappers like struct Meters { value: f64 }, where you want 12.5 and not {"value":12.5}.
Converting through another type with from, into, and try_from
Sometimes the serialized shape differs from the in-memory shape, or the type has rules that the derive cannot express. The attributes from, into, and try_from hand the work to a different type.
#[serde(into = "T")]serializes by converting the value intoTfirst. Serde only has&self, so the type must implementCloneandInto<T>.#[serde(from = "T")]deserializes aT, then converts it withFrom<T>.#[serde(try_from = "T")]does the same withTryFrom<T>. The error type must implementDisplay, and the message becomes the deserialization error.
This is a clean way to keep an invariant. The type cannot be built from JSON unless it passes validation:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
struct Email(String);
impl TryFrom<String> for Email {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.contains('@') {
Ok(Email(value))
} else {
Err(format!("`{value}` is not an email address"))
}
}
}
impl From<Email> for String {
fn from(email: Email) -> String {
email.0
}
}
fn main() {
let good: Result<Email, _> = serde_json::from_str(r#""[email protected]""#);
println!("{good:?}"); // Ok(Email("[email protected]"))
let bad: Result<Email, _> = serde_json::from_str(r#""nope""#);
// `nope` is not an email address at line 1 column ...
println!("{}", bad.unwrap_err());
}Keep in mind that the derive on such a type is not really used for the fields. Serde follows the conversion path instead. Field attributes on Email itself would be ignored for this path, and any shape rules belong on the intermediate type.
Other container attributes you will meet
#[serde(rename = "Name")]on a container sets the type name that formats which record names, such as some binary ones, see. JSON ignores it.#[serde(bound = "T: Trait")]replaces the trait bounds that the derive infers for generic types. Reach for it only when inference produces a bound that is wrong or too strict.#[serde(crate = "path")]points the generated code at a re-exported copy of serde. It matters when you write a macro crate that re-exports serde.tag,content, anduntaggedchange how enums are laid out. The next chapter covers them in detail.
Common mistakes
- Expecting
rename_allon an enum to rename the fields of its struct variants. It renames the variants only. - Adding
deny_unknown_fieldsto a type that also usesflatten. - Using
#[serde(into = "T")]on a type that is notClone. The compile error points into generated code, which is hard to read. - Writing
#[serde(default)]on a container with noDefaultimplementation. - Assuming a default fills in a field whose key is present but
null. A presentnullis not missing, so it follows normal type rules.
Exercise
A type Percent(u8) must only deserialize values from 0 to 100 and must serialize as a bare number such as 42. Which container attribute pairing achieves this, and what does the TryFrom implementation need to satisfy?
Show answer
Use #[serde(try_from = "u8", into = "u8")] and derive Clone, Serialize, and Deserialize. Implement TryFrom<u8> for Percent that returns Ok for values up to 100 and an Err otherwise, where the error type implements Display (a String works). Also implement From<Percent> for u8. The type needs Clone because into converts a clone of &self.
Exercise
You add #[serde(rename_all = "camelCase")] to enum Shape { Circle { corner_radius: f64 } }. What names appear in the JSON for the variant and for the field, and how would you make the field cornerRadius without renaming it by hand?
Show answer
The variant is written as circle and the field stays corner_radius, because rename_all on an enum affects only variant names. To rename the fields inside variants, add rename_all_fields = "camelCase" to the enum (serde 1.0.186 or later), or put #[serde(rename = "cornerRadius")] on the field.