skip to content

In Rust with Serde, what do `rename_all = "camelCase"`, `default`, `skip_serializing_if` and `deny_unknown_fields` change for a webhook `OrderEvent` struct?

level: middleimportance: must knowfreq 70%

answer

  1. wire names vs Rust names
  2. absent is not null
  3. output-only skipping
  4. strictness is opt-in

basics

~20 s

rename_all maps snake_case fields to camelCase keys, default fills an absent field from Default, skip_serializing_if omits a field on output when its predicate is true, and deny_unknown_fields turns unexpected keys into errors instead of ignoring them.

solid answer

~40 s

These attributes change only the generated impls, never the Rust struct. `#[serde(rename_all = "camelCase")]` on the container makes `order_id` read and write as `orderId`; a field-level `#[serde(rename = "type")]` overrides it, which is how a field called `kind` maps to a key that is a Rust keyword. `#[serde(default)]` fills a field that is absent from the input with `Default::default()`, or with a function given as `default = "path"`, but an explicit `null` for a `u32` is still an `invalid type: null` error. `#[serde(skip_serializing_if = "Option::is_none")]` drops `None` from the output and has no effect on input. `#[serde(deny_unknown_fields)]` makes an extra key such as `currency` fail with an error that lists the expected names; without it the key is ignored.

code

rust · 23 lines
rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct OrderEvent {
    order_id: u64,
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    retry_count: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    coupon_code: Option<String>,
}

fn main() {
    let body = r#"{"orderId": 42, "type": "order.paid"}"#;
    let event: OrderEvent = serde_json::from_str(body).unwrap();
    println!("{event:?}");
    println!("{}", serde_json::to_string(&event).unwrap());

    let extra = r#"{"orderId": 42, "type": "order.paid", "currency": "EUR"}"#;
    println!("{}", serde_json::from_str::<OrderEvent>(extra).unwrap_err());
}

go deeper

for a junior

Recall that rename and rename_all change only the JSON key names, and that default fills a missing field. Be able to write the attributes from memory.

for a middle

Explain absent versus null, why skip_serializing_if is output-only, and that unknown keys are ignored unless deny_unknown_fields is on.

for a senior

Show judgment on strictness: tolerate unknown keys from external senders, reject them in configuration, and know flatten's buffering and its clash with deny_unknown_fields.

for a principal

Treat the attribute set as a contract policy: decide per boundary whether payloads are strict or tolerant, and make the choice visible in review instead of per-struct habit.

## Attributes shape the generated impls Serde's derive reads `#[serde(...)]` attributes and changes the code it generates. Nothing about the Rust struct changes: your code still says `event.order_id`. There are two places to put them: - **Container attributes** go on the struct or enum: `rename_all`, `deny_unknown_fields`, a struct-wide `default`. - **Field attributes** go on one field: `rename`, `default`, `skip`, `skip_serializing_if`, `flatten`, `deserialize_with`. A webhook payload is the classic place they all meet, because the sender's JSON conventions rarely match Rust's. ## Renaming: `rename_all` and `rename` Rust fields are `snake_case`; many JSON APIs use `camelCase`. `#[serde(rename_all = "camelCase")]` on the container converts every field name in both directions, so `order_id` is read from and written as `orderId`. The accepted conventions are `"lowercase"`, `"UPPERCASE"`, `"PascalCase"`, `"camelCase"`, `"snake_case"`, `"SCREAMING_SNAKE_CASE"`, `"kebab-case"` and `"SCREAMING-KEBAB-CASE"`. On an enum, `rename_all` renames the variants rather than fields, and `rename_all_fields` renames the fields inside its struct variants. A field-level `#[serde(rename = "type")]` **wins over** `rename_all` for that field. It is the standard way to read a key that is a Rust keyword: the field is called `kind`, the wire name is `type`. Both attributes accept separate names per direction (`rename(serialize = "...", deserialize = "...")`), and `#[serde(alias = "...")]` adds an extra name accepted on input only, which helps when a sender renames a key. ## Absent fields: `default`, `Option` and `skip` | Declaration | Key absent | Key present as `null` | |---|---|---| | `retry_count: u32` | error: ``missing field `retryCount` `` | error: `invalid type: null, expected u32` | | `#[serde(default)] retry_count: u32` | `0` from `Default::default()` | error: `invalid type: null, expected u32` | | `coupon_code: Option<String>` | `None` | `None` | | `#[serde(skip)] received_at: Option<u64>` | never read; `Default::default()` | the key counts as unknown | The row people get wrong is the second: **`default` covers an absent key, not a `null` value**. If a sender writes `null` for a number, the field must be an `Option`, or you need a custom deserializer. `#[serde(default = "path")]` calls a function of type `fn() -> T` instead of `Default::default()`, and `#[serde(default)]` on the whole struct fills every absent field from the struct's own `Default` impl. `#[serde(skip)]` removes a field from both directions. It is how you keep local state, such as a receive timestamp, in the same struct without it ever appearing on the wire. ## Shaping output with `skip_serializing_if` `#[serde(skip_serializing_if = "Option::is_none")]` calls the named function, which must be callable as `fn(&T) -> bool`, before writing the field and omits the key when it returns `true`. `Vec::is_empty` and `String::is_empty` are the other common predicates. It affects **serialisation only**: the field is still read from input as usual. Pair it with `default` when the field is not an `Option`, so a document you wrote can be read back. ## Unknown keys: ignore, reject or capture By default the derived impl **ignores** keys it does not recognise, for self-describing formats such as JSON. That tolerance lets a sender add fields without breaking you. `#[serde(deny_unknown_fields)]` flips it: an extra key fails with an error that names it and lists the expected keys, after renaming: ```plaintext unknown field `currency`, expected one of `orderId`, `type`, `retryCount`, `couponCode` ``` The third option is `#[serde(flatten)]` on a `HashMap<String, serde_json::Value>` field, which collects every unclaimed key into the map and writes them back out at the top level. It has costs: the derived impl switches from reading a struct to reading a map and buffers the unclaimed entries, and Serde's documentation says `flatten` is not supported in combination with `deny_unknown_fields`, on either the outer or the flattened struct. ## Choosing for a webhook 1. Match the sender's naming once with `rename_all`, then override the exceptions with `rename`. 2. Make every field the sender may omit either an `Option` or `#[serde(default)]`, depending on whether "absent" and "zero" mean the same thing to you. 3. Decide strictness deliberately: ignoring unknown keys is right for a third party that adds fields; `deny_unknown_fields` suits configuration files and internal contracts, where a typo should fail loudly. 4. Keep output lean with `skip_serializing_if` when you also send the type on, so `None` does not travel as `null`. Which serialisation format to pick, and how schemas evolve across versions in general, belong to the material on serialisation formats.

  • What is the difference between #[serde(skip)] and #[serde(skip_serializing_if = "Option::is_none")]?
    `skip` removes the field from both directions: it is never written or read, and on deserialization it takes `Default::default()` or the `default = "..."` function. `skip_serializing_if` is output-only and conditional: the field is still read from input, and on output it is omitted only when the predicate returns true.
  • How do you keep unknown webhook keys instead of dropping or rejecting them?
    Add a `#[serde(flatten)]` field of type `HashMap<String, serde_json::Value>`: every key the struct does not declare lands there, and serializing writes them back at the top level. The derived impl then reads a map and buffers the unclaimed keys, and Serde's docs say `flatten` is not supported together with `deny_unknown_fields`.
  • A sender renames `coupon` to `couponCode`; how do you accept both during the migration?
    Keep the field named for the new key and add `#[serde(alias = "coupon")]`. An alias is accepted on input only, so the struct reads either key and always writes the new one. A body that carries both keys is rejected with ``duplicate field `couponCode` ``, because they target the same field.

  • rename_all renames the Rust fields too, so code must say event.orderId.
  • #[serde(default)] also turns an explicit null into the default value.
  • skip_serializing_if also skips the field when deserializing.
  • By default Serde rejects unknown keys, so new webhook fields break parsing.
  • A field-level rename is ignored when the container has rename_all.