Sub topic 6
Shaping fields with attributes
This chapter assumes you can derive Serialize and Deserialize and round-trip a struct through serde_json. It also assumes you can read a Result returned by serde_json::from_str. Container-level attributes such as rename_all and deny_unknown_fields have their own chapter, so this one covers only attributes placed on a single field.
Why field attributes exist
The derive macros map each Rust field to a key with the same name, and they require every key to be present when deserializing. Real JSON rarely fits that. Keys use other naming styles, optional keys are missing, secrets must not be written out, and some objects mix known keys with arbitrary extras.
A field attribute is written as #[serde(...)] directly above a field. It changes how the derived code treats that one field and leaves the rest of the struct alone.
| Attribute | Effect |
|---|---|
| `rename = "x"` | Uses `x` as the key in both directions |
| `alias = "x"` | Also accepts `x` as a key when deserializing |
| `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 |
| `skip_serializing` | Never writes the field |
| `skip_deserializing` | Never reads the field and fills it with a default |
| `skip_serializing_if = "path"` | Omits the field when the function returns `true` |
| `flatten` | Merges the field's keys into the parent object |
Renaming and defaults
rename sets the key name. If the input and output names differ, pass both: rename(serialize = "out", deserialize = "in"). alias adds extra accepted names for reading and does not change what is written.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Account {
#[serde(rename = "id")]
account_id: u32,
#[serde(alias = "login")]
username: String,
#[serde(default)]
active: bool,
#[serde(default = "default_role")]
role: String,
}
fn default_role() -> String {
"viewer".to_string()
}
fn main() -> Result<(), serde_json::Error> {
let account: Account = serde_json::from_str(r#"{"id":7,"login":"ada"}"#)?;
println!("{account:?}");
println!("{}", serde_json::to_string(&account)?);
Ok(())
}This prints:
Account { account_id: 7, username: "ada", active: false, role: "viewer" }
{"id":7,"username":"ada","active":false,"role":"viewer"}The input used login, but the output uses username, because alias affects only reading. #[serde(default)] needs the field type to implement Default. #[serde(default = "default_role")] calls a function that takes no arguments and returns the field type.
What happens when a key is missing
The derived Deserialize handles a missing key in a fixed order. The diagram shows the order.
Note the Option rule. A plain Option<String> field accepts a missing key without any attribute. A Vec<String> or u32 field does not, and fails with an error that starts missing field followed by the field name. Add default when a missing key should be legal.
Skipping fields
Three skip attributes cover different situations.
skipremoves the field from the serialized form and from deserialization. The field must implementDefault, or you must givedefault = "path".skip_serializinghides a field on output but still reads it. Use it for values such as passwords that may arrive but must never be echoed.skip_deserializingdoes the opposite. The field is written but never read, and it gets its default value.
skip_serializing_if takes a function that receives &FieldType and returns bool. It is mostly used to drop None and empty collections.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Session {
user: String,
#[serde(skip)]
cache: Vec<String>,
#[serde(skip_serializing)]
password: String,
#[serde(skip_serializing_if = "Option::is_none")]
note: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
tags: Vec<String>,
}
fn main() -> Result<(), serde_json::Error> {
let session: Session = serde_json::from_str(r#"{"user":"ada","password":"pw"}"#)?;
println!("{session:?}");
println!("{}", serde_json::to_string(&session)?);
Ok(())
}This prints:
Session { user: "ada", cache: [], password: "pw", note: None, tags: [] }
{"user":"ada"}The password field was read but not written. note and tags were left out because they were empty.
Pair skip_serializing_if with default when the output must be readable again. note is an Option, so a missing key already becomes None. tags is a Vec, so it needs default. Without it, reading back the JSON you just wrote would fail with missing field.
Flattening nested structs and catching extras
flatten takes a field whose type is a struct or map and inlines its keys into the parent object. It has two common uses: sharing a group of fields across several types, and collecting unknown keys.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
struct Pagination {
page: u32,
per_page: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Response {
status: String,
#[serde(flatten)]
pagination: Pagination,
#[serde(flatten)]
extra: HashMap<String, Value>,
}
fn main() -> Result<(), serde_json::Error> {
let input = r#"{"status":"ok","page":2,"per_page":50,"trace":"abc"}"#;
let response: Response = serde_json::from_str(input)?;
println!("{response:?}");
println!("{}", serde_json::to_string(&response)?);
Ok(())
}This prints:
Response { status: "ok", pagination: Pagination { page: 2, per_page: 50 }, extra: {"trace": String("abc")} }
{"status":"ok","page":2,"per_page":50,"trace":"abc"}The JSON is flat, but the Rust type has structure. During deserialization, serde reads the keys it recognizes directly, buffers the rest, and offers the buffered keys to each flattened field in declaration order. pagination takes page and per_page. The map is declared last, so it receives only what is left, which is trace.
Flatten has costs and limits:
- The buffering means flattened input cannot be borrowed from the source text, so it works against zero-copy deserialization.
- A struct with a flattened field cannot use
deny_unknown_fields. - Keys that appear in both the parent and a flattened struct are ambiguous. Avoid the overlap.
- Number handling can be surprising with some formats, because buffered values lose their original type information.
Common mistakes
- Using
renamewhen you only need an extra input name.renamechanges the output as well, which can break consumers. Usealiasfor read-only compatibility. - Adding
skip_serializing_ifto a non-Optionfield and then failing to read the result back, becausedefaultis missing. - Writing the path with the wrong signature.
skip_serializing_iftakes a function from&Ttobool, soOption::is_noneworks forOption<T>fields. For au32, write a small helper such asfn is_zero(n: &u32) -> bool { *n == 0 }. - Skipping a field that has no
Defaultimplementation. The derive then fails to compile, and the fix isdefault = "path". - Expecting
aliasto work in the output direction.
Fields that need custom conversion logic, such as writing a number as a hex string, use serialize_with and deserialize_with. A later chapter covers them.
Exercises
Exercise
A struct has the field #[serde(skip_serializing_if = "Vec::is_empty")] tags: Vec<String>. The JSON written for an empty list is {"user":"ada"}. Reading it back with serde_json::from_str fails. What is the error, and what is the smallest fix?
Show answer
The error is missing field tags`. A Vec field is not optional and has no fallback, so a missing key is an error. Add default so the attribute becomes #[serde(default, skipserializingif = "Vec::is_empty")]`. A missing key then deserializes as an empty vector.
Exercise
You must read a field named login from old clients and username from new clients, but always write username. Which attribute do you put on the field, and why not rename = "login"?
Show answer
Use #[serde(alias = "login")] on a field named username. alias adds an accepted name for reading only, so output stays username. rename = "login" would replace the name in both directions, and the program would then write login and reject username.
Exercise
In struct Response, two fields are both marked #[serde(flatten)]: a Pagination struct first and a HashMap<String, Value> second. The input has keys status, page, per_page and trace. Which keys end up in the map, and what would change if the map were declared first?
Show answer
Only trace ends up in the map, because Pagination claims page and per_page before the map sees the leftovers. If the map were declared first, it would try to take every unclaimed key and could capture page and per_page, leaving Pagination without its fields and failing with a missing field error. Put the catch-all map last.