Sub topic 6
Shaping fields with attributes
This chapter assumes you can derive Serialize and Deserialize and round-trip a struct through serde_json. Field attributes are #[serde(...)] annotations placed on individual struct fields. They change how one field is named, filled in, skipped, or merged, and the rest of the struct keeps the derived behavior.
The common field attributes
| Attribute | Effect |
|---|---|
| `rename = "x"` | Uses `x` as the key in both directions. |
| `alias = "x"` | Also accepts `x` when deserializing. Serialization is unchanged. |
| `default` | Uses `Default::default()` when the key is missing. |
| `default = "path"` | Calls the function at `path` when the key is missing. |
| `skip` | Ignores the field in both directions. The type must implement `Default`. |
| `skip_serializing_if = "path"` | Omits the field when the function returns `true`. |
| `flatten` | Merges the fields of a nested struct or map into the parent object. |
rename_all and deny_unknown_fields are container-level attributes, so they are covered in the next chapter.
One struct, several attributes
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
struct Account {
#[serde(rename = "userId")]
user_id: u32,
#[serde(alias = "mail")]
email: String,
#[serde(default)]
retries: u32,
#[serde(skip_serializing_if = "Option::is_none")]
nickname: Option<String>,
#[serde(skip)]
cache: Vec<String>,
#[serde(flatten)]
extra: HashMap<String, serde_json::Value>,
}
fn main() -> Result<(), serde_json::Error> {
let input = r#"{"userId":7,"mail":"[email protected]","theme":"dark"}"#;
let account: Account = serde_json::from_str(input)?;
println!("{account:?}");
println!("{}", serde_json::to_string(&account)?);
// {"userId":7,"email":"[email protected]","retries":0,"theme":"dark"}
Ok(())
}Each attribute shows up in this run:
userIdfillsuser_idbecause ofrename.- The input key
mailis accepted because ofalias, but the output usesemail. retriesis absent from the input, so it becomes0.nicknameisNoneand is left out of the output instead of appearing asnull.cachenever appears in either direction.themematches no named field, soflattencollects it intoextra. On output it is written back at the top level.
Defaults from a function
Plain default only helps when the type's Default value is what you want. For anything else, point to a function.
use serde::Deserialize;
fn default_port() -> u16 {
8080
}
#[derive(Debug, Deserialize)]
struct Server {
host: String,
#[serde(default = "default_port")]
port: u16,
}
fn main() -> Result<(), serde_json::Error> {
let server: Server = serde_json::from_str(r#"{"host":"localhost"}"#)?;
println!("{server:?}"); // Server { host: "localhost", port: 8080 }
Ok(())
}Common errors
- Missing key on a non-
Optionfield. Deserialization fails withmissing field. Adddefault, or change the field toOption<T>. AnOptionfield is also accepted when its key is missing. skipon a type withoutDefault. The derive fails to compile. Useskip_serializingandskip_deserializingseparately, and give the skipped direction adefault = "path"function.renameon only one side.renameapplies to both directions. Usealiaswhen you only need to accept extra input names. Userename(serialize = "...", deserialize = "...")for different names in each direction.flattenwithdeny_unknown_fields. These two do not work together. A flattened field collects unknown keys, so serde does not support combining them.
Exercise
A struct has a field tags: Vec<String>. You want JSON without the key when the list is empty, and you want input without the key to give an empty list. Which attributes do you add?
Show answer
#[serde(default, skip_serializing_if = "Vec::is_empty")]. default supplies an empty Vec when the key is missing. skip_serializing_if calls Vec::is_empty and omits the key when it returns true.