In Rust, how does Serde write an `OrderEvent` enum to JSON by default, and what do `tag`, `content` and `untagged` change?
answer
- variant name as the outer key
- tag beside the fields
- tag and content side by side
- first variant that succeeds
basics
~20 sBy default Serde externally tags an enum: {"Paid": {...}}. #[serde(tag = "type")] puts the variant name inside the object, content = "data" nests the fields beside the tag, and untagged writes only the fields, trying each variant in order.
solid answer
~40 sSerde's default is **externally tagged**: `OrderEvent::Paid { .. }` becomes `{"Paid":{"order_id":42,...}}`, which handles every variant kind and works across text and binary formats. `#[serde(tag = "type")]` makes it **internally tagged**, `{"type":"paid","order_id":42,...}` once `rename_all = "snake_case"` lowercases the variant names; that is the usual webhook shape, but it rejects tuple variants at compile time and buffers the object to find the tag. `#[serde(tag = "type", content = "data")]` is **adjacently tagged**: `{"type":"paid","data":{...}}`. `#[serde(untagged)]` writes only the fields and on input tries each variant in declaration order, keeping the first that succeeds, so an earlier variant whose fields are a subset of a later one's swallows it, and a total failure reports only `data did not match any variant of untagged enum OrderEvent`.
code
rust · 19 linesuse serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum OrderEvent {
Paid { order_id: u64, amount_cents: u64 },
Cancelled { order_id: u64 },
}
fn main() {
let paid = OrderEvent::Paid { order_id: 42, amount_cents: 1999 };
println!("{}", serde_json::to_string(&paid).unwrap());
let body = r#"{"order_id": 42, "type": "cancelled"}"#;
println!("{:?}", serde_json::from_str::<OrderEvent>(body).unwrap());
let bad = r#"{"type": "refunded", "order_id": 42}"#;
println!("{}", serde_json::from_str::<OrderEvent>(bad).unwrap_err());
}go deeper
Recall that the default output nests the data under the variant name, and that tag = "type" produces the flat shape most JSON APIs use.
Explain all four representations with their JSON, why internal tagging rejects tuple variants, and how rename_all renames variants.
Show the production traps: untagged order and its vague error, buffering in internal and untagged forms, and lost error positions inside a buffered variant.
Weigh representation as a public contract: once consumers parse a shape, changing it is a breaking change, so pick the tagged form deliberately at the start.
## The four representations A Rust enum carries a **variant** (which case it is) plus that variant's data. JSON has no enum type, so Serde must choose how to write the variant's identity. It offers four **enum representations**, selected by container attributes on the enum: | Attribute | JSON for `Paid { order_id: 42, amount_cents: 1999 }` | Variant kinds allowed | |---|---|---| | none (externally tagged) | `{"Paid":{"order_id":42,"amount_cents":1999}}` | all | | `tag = "type"` (internally tagged) | `{"type":"paid","order_id":42,"amount_cents":1999}` | struct, newtype of a struct or map, unit | | `tag = "type", content = "data"` (adjacently tagged) | `{"type":"paid","data":{...}}` | all | | `untagged` | `{"order_id":42,"amount_cents":1999}` | all | The lowercase `"paid"` comes from `rename_all = "snake_case"` on the enum, which renames **variants** the way it renames fields on a struct. ## Externally tagged, the default With no attribute, the variant name is the single key of an outer object and the data is its value; a unit variant such as `Pending` is written as the bare string `"Pending"`. Serde's documentation stresses the property that makes this the default: the deserializer learns the variant **before** it parses the content, so it works for every kind of variant and in binary formats too. It is also the only representation that works without an allocator. Its weakness is readability: most JSON APIs do not nest events this way. ## Internally tagged: the webhook shape `#[serde(tag = "type")]` puts the variant name in a field inside the object, next to the variant's own fields. This matches how most event payloads look, so it is the usual choice for a webhook `OrderEvent`. What to know about it: - **Tuple variants are rejected at compile time.** `Paid(u64, u64)` would serialise as an array, which has no room for a `type` key, and serde_derive stops with `#[serde(tag = "...")] cannot be used with tuple variants`. - **The tag need not come first.** `{"order_id":42,"type":"cancelled"}` deserializes fine, because the derived impl first reads the whole object into an internal buffer, finds the tag, then deserializes the variant from the buffer. - That buffering needs serde's `alloc` feature (on by default) and costs a copy of the object. It also changes errors: a missing field inside a variant can arrive without a line and column, as ``missing field `amount_cents` `` did in a test with serde_json, because the error is raised from the buffered copy rather than while serde_json is reading the text. - An unrecognised tag is a clear error: ``unknown variant `refunded`, expected `paid` or `cancelled` ``. ## Adjacently tagged `#[serde(tag = "type", content = "data")]` writes two sibling keys, one naming the variant and one holding its data. It accepts tuple and newtype variants, which internal tagging cannot, and suits envelopes where the payload is not itself an object, such as `{"type":"Str","data":"text"}`. Like internal tagging, deserializing it needs serde's `alloc` feature, which is on by default. ## Untagged and its traps `#[serde(untagged)]` writes no tag at all. On input Serde buffers the value and tries each variant **in declaration order**, returning the first that deserializes successfully. Three consequences: 1. **Order decides.** If `Cancelled { order_id }` is declared before `Paid { order_id, amount_cents }`, a Paid body parses as `Cancelled`, because the extra key is ignored by default. 2. **Errors are vague.** When no variant fits, serde_derive's message is just `data did not match any variant of untagged enum OrderEvent`; which field broke each attempt is not reported. 3. **Every attempt re-reads the buffer**, so a large payload with many variants does repeated work. Untagged is the right tool when the data really has no tag and the shapes are disjoint, for example a value that is either a number or a list. ## Choosing a representation - **You control both sides:** keep the default, or use internal tagging for readability. - **Consuming someone else's events:** match their shape; internal tagging fits most `"type"`-discriminated payloads. - **Payloads that are not objects:** adjacent tagging. - **No discriminator at all:** untagged, with variants ordered from most to least specific, and tests for each shape. Sum types and pattern matching as general ideas belong to the material on Rust enums; Serde only decides how a variant is spelled on the wire.
- Why does #[serde(tag = "type")] refuse an enum with a tuple variant such as Paid(u64, u64)?An internally tagged variant's data must share one JSON object with the tag, and a tuple variant serializes as an array, which cannot hold a `type` key. serde_derive rejects it at compile time with `#[serde(tag = "...")] cannot be used with tuple variants`. Use a struct variant, a newtype variant wrapping a struct, or adjacent tagging.
- An untagged OrderEvent parses every Paid event as Cancelled. Why, and what fixes it?Untagged deserialization tries variants in declaration order and keeps the first success. `Cancelled { order_id }` declared before `Paid { order_id, amount_cents }` matches a Paid body, because the extra `amount_cents` key is ignored. Declare the more specific variant first, or switch to a tagged representation so the payload names its variant.
- By default Serde writes a "type" field inside the object naming the variant.
- An internally tagged enum can hold tuple variants like Paid(u64, u64).
- An untagged enum picks the variant that fits best, not the first that succeeds.
- The tag key must be the first key in the JSON object.
- Untagged errors say which variant came closest and which field failed.