Sub topic 8
Choosing an enum representation
A Rust enum has no single JSON shape. Serde has four ways to write one, and the one you pick decides which JSON your code produces and accepts. This chapter assumes you can derive Serialize and Deserialize and call serde_json::to_string and from_str. You should also know the container attributes rename_all and deny_unknown_fields.
The four representations
| Representation | Attribute | Variant `Click { x: 1, y: 2 }` becomes |
|---|---|---|
| Externally tagged | none (default) | `{"Click":{"x":1,"y":2}}` |
| Internally tagged | `tag = "type"` | `{"type":"Click","x":1,"y":2}` |
| Adjacently tagged | `tag = "t", content = "c"` | `{"t":"Click","c":{"x":1,"y":2}}` |
| Untagged | `untagged` | `{"x":1,"y":2}` |
The attribute goes on the enum, so every variant in that enum uses the same representation. The tag is the piece of data that tells the deserializer which variant it is looking at. Three of the representations store a tag explicitly. The untagged one stores none, so the deserializer has to infer the variant from the content.
Externally tagged: the default
With no attribute, the variant name is the key of a single-entry object. The variant's data is the value.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
enum Command {
Click { x: i32, y: i32 },
Key(char),
Quit,
}
fn main() -> Result<(), serde_json::Error> {
for cmd in [Command::Click { x: 1, y: 2 }, Command::Key('a'), Command::Quit] {
println!("{}", serde_json::to_string(&cmd)?);
}
// {"Click":{"x":1,"y":2}}
// {"Key":"a"}
// "Quit"
let back: Command = serde_json::from_str(r#"{"Key":"z"}"#)?;
println!("{back:?}");
Ok(())
}A unit variant such as Quit becomes a bare string, not an object. A reader of the JSON must handle both strings and objects. This form works for every kind of variant, which is why it is the default. It is also the most compact form for Rust-to-Rust communication. It is often not the shape an existing API uses.
Internally tagged: the tag sits beside the fields
#[serde(tag = "type")] puts the variant name in a field of the same object as the variant's own fields. Most JSON APIs that carry a "type" or "kind" discriminator use this shape.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct TextBody {
body: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Message {
Text(TextBody),
Move { dx: i32, dy: i32 },
Ping,
}
fn main() -> Result<(), serde_json::Error> {
let msg = Message::Text(TextBody { body: "hi".into() });
println!("{}", serde_json::to_string(&msg)?); // {"type":"text","body":"hi"}
println!("{}", serde_json::to_string(&Message::Ping)?); // {"type":"ping"}
let back: Message = serde_json::from_str(r#"{"dx":5,"type":"move","dy":-1}"#)?;
println!("{back:?}");
Ok(())
}The tag may appear anywhere in the input object. Serde buffers the fields until it finds it, so the key order does not matter.
Internal tagging has limits, because the tag has to live inside a map:
- A tuple variant with more than one field cannot be represented. The derive rejects it at compile time.
- A newtype variant must wrap something that serializes as a struct or map, such as
TextBodyabove. Wrapping acharor aStringcompiles, but serializing it fails at run time. - Deserialization goes through a buffer of the whole object. This costs some speed, and it can interact badly with
#[serde(borrow)]on variant fields.
Tolerating unknown tags
By default an unknown tag value is an error. A unit variant marked #[serde(other)] catches any tag the enum does not list. This works on internally and adjacently tagged enums.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Incoming {
Click { x: i32, y: i32 },
#[serde(other)]
Unknown,
}
fn main() -> Result<(), serde_json::Error> {
let ev: Incoming = serde_json::from_str(r#"{"type":"scroll","dy":3}"#)?;
println!("{ev:?}"); // Unknown
Ok(())
}The fallback discards the fields of the unrecognized event. Use it when a newer sender may add event types that an older receiver should skip, not reject.
Adjacently tagged: tag and content side by side
#[serde(tag = "t", content = "c")] writes the tag and the data as two sibling keys. The data is always in one place, whatever the variant looks like.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum Packet {
Click { x: i32, y: i32 },
Key(char),
Quit,
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Packet::Key('a'))?); // {"t":"Key","c":"a"}
println!("{}", serde_json::to_string(&Packet::Quit)?); // {"t":"Quit"}
let back: Packet = serde_json::from_str(r#"{"c":{"x":1,"y":2},"t":"Click"}"#)?;
println!("{back:?}");
Ok(())
}Unlike internal tagging, this form handles tuple variants, newtype variants wrapping primitives, and unit variants. The cost is an extra level of nesting. Choose it when a variant holds a bare value, such as a string or a number, and the format still needs a named discriminator.
Untagged: the content decides
With #[serde(untagged)], nothing in the output names the variant. When deserializing, serde tries each variant in declaration order and keeps the first one that succeeds.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Id {
Num(u64),
Text(String),
}
fn main() -> Result<(), serde_json::Error> {
let ids: Vec<Id> = serde_json::from_str(r#"[7,"seven"]"#)?;
println!("{ids:?}"); // [Num(7), Text("seven")]
let err = serde_json::from_str::<Id>("true").unwrap_err();
println!("{err}"); // data did not match any variant of untagged enum Id
Ok(())
}Untagged enums are the right tool when an API accepts several shapes for one field, such as a number or a string. They have three costs:
- Order matters. If a broader variant comes first, it hides the narrower one. With
enum Num { Float(f64), Int(i64) }, the input5parses asFloat(5.0), becauseserde_jsonaccepts an integer where anf64is expected. Put the most specific variant first. - Errors are vague. When every variant fails, serde reports only that the data matched none of them. It does not say which variant came closest or why it failed. For a precise message, use a tagged form.
- Deserialization is slower. Serde buffers the input and retries it once per variant.
Picking one
Work through these questions in order:
- If you control both sides and nobody else reads the JSON, keep the default.
- If an existing API has a discriminator field next to the other fields, use
tag. Check that every variant is a struct variant, a unit variant, or a newtype around a struct. - If the API uses a tag key and a separate payload key, use
tagandcontent. - If the API has no discriminator and the shapes are distinguishable, use
untagged. Test it with samples of every shape. - If the enum has only unit variants and the API expects plain strings, no extra attribute is needed beyond
rename_all. For integer discriminants, the separateserde_reprcrate covers that case.
The representation also applies to other formats. The same attributes work with TOML or YAML, but not every format can express every shape. If a format has no way to write a tagged enum, the failure shows up at run time, not at compile time. Test a round trip in the target format.
Exercise
A client sends {"kind":"circle","radius":2.5} or {"kind":"square","side":4.0}. Which representation fits, and why does Shape::Circle(f64) fail to work as a variant under it?
Show answer
Use internal tagging with #[serde(tag = "kind", rename_all = "snake_case")] and struct variants such as Circle { radius: f64 } and Square { side: f64 }. The tag must sit in the same object as the other fields. A newtype variant wrapping a bare f64 has no field to merge the tag into, so serializing it fails at run time.
Exercise
Given #[serde(untagged)] enum Num { Float(f64), Int(i64) }, what does serde_json::from_str::<Num>("5") return, and how do you get Int(5) instead?
Show answer
It returns Float(5.0), because variants are tried in declaration order and f64 accepts the integer 5. Declare Int(i64) before Float(f64). The input 5 then matches Int first, and 5.5 fails Int and falls through to Float.