In Rust, a webhook sends `amount_cents` as `1999` or `"1999"`; how do you accept both with Serde, and why prefer a Visitor over an untagged enum?
answer
- a hook on one field
- one method per data-model type
- expecting writes the error text
- untagged buffers and guesses
basics
~20 sMark the field #[serde(deserialize_with = "cents")] and write a Visitor with visit_u64 and visit_str. Unlike an untagged helper enum, it reads the value without buffering and its errors say exactly what arrived and what was expected.
solid answer
~40 s`#[serde(deserialize_with = "cents")]` swaps in a function `fn cents<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error>` for that one field. Inside, a `Visitor` implements one method per data-model type it accepts: `visit_u64` returns the number, `visit_str` parses the digits, and every method left out keeps its default, which either forwards to a wider method or rejects the input as an invalid type. `expecting` supplies the error text, so `"19.99"` fails with `invalid value: string "19.99", expected an amount in cents as a number or a digit string`, plus line and column. An `#[serde(untagged)]` helper enum also works, but it buffers the value, tries each variant, and when none fits reports only `data did not match any variant of untagged enum NumOrText`. Both depend on JSON being self-describing: `deserialize_any` rules out formats such as Postcard.
code
rust · 41 linesuse std::fmt;
use serde::Deserialize;
use serde::de::{self, Deserializer, Visitor};
#[derive(Deserialize)]
struct OrderEvent {
order_id: u64,
#[serde(deserialize_with = "cents")]
amount_cents: u64,
}
fn cents<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
struct CentsVisitor;
impl<'de> Visitor<'de> for CentsVisitor {
type Value = u64;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("an amount in cents as a number or a digit string")
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<u64, E> {
Ok(v)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<u64, E> {
v.parse().map_err(|_| E::invalid_value(de::Unexpected::Str(v), &self))
}
}
d.deserialize_any(CentsVisitor)
}
fn main() {
for body in [
r#"{"order_id": 42, "amount_cents": 1999}"#,
r#"{"order_id": 42, "amount_cents": "1999"}"#,
r#"{"order_id": 42, "amount_cents": "19.99"}"#,
] {
match serde_json::from_str::<OrderEvent>(body) {
Ok(e) => println!("{} {}", e.order_id, e.amount_cents),
Err(err) => println!("error: {err}"),
}
}
}go deeper
Recall that deserialize_with points one field at a custom function, and that serialize_with does the same for output.
Explain the Visitor flow: the format calls one visit method, defaults reject everything else, and expecting writes the error text.
Show why the visitor beats an untagged helper on an external webhook: no buffering, invalid type versus invalid value, and errors you can act on from logs.
Decide where tolerance lives: accept a sender's inconsistency in one tested edge function rather than letting loose types spread through the domain model.
## Field-level hooks Sometimes the derived impl is right for a struct except for one field. Serde has three field attributes for that: - **`#[serde(deserialize_with = "path")]`** calls a function `fn<'de, D>(D) -> Result<T, D::Error> where D: Deserializer<'de>` instead of the field type's own `Deserialize` impl. - **`#[serde(serialize_with = "path")]`** calls `fn<S>(&T, S) -> Result<S::Ok, S::Error> where S: Serializer` on output. - **`#[serde(with = "module")]`** uses `module::serialize` and `module::deserialize` together. Serde's documentation notes that a field using `deserialize_with` does not need to implement `Deserialize` itself, which is also how you handle a foreign type you cannot add an impl to. Writing a whole `impl Deserialize` by hand is the same skill applied to a type rather than a field. ## How a Visitor works A `Visitor` is the type that receives values from a format. The flow is: 1. Your function calls a method on the `Deserializer`, such as `deserialize_any(visitor)` or `deserialize_u64(visitor)`, to say what it wants. 2. The format reads the next value and calls **exactly one** visit method that matches what it found: `visit_u64` for a non-negative JSON integer, `visit_i64` for a negative one, `visit_str` for a string, `visit_bool`, `visit_map` and so on. 3. Every visit method has a **default implementation**. Most return an `invalid type` error; the narrower ones forward to a wider one, so `visit_u8` calls `visit_u64` and `visit_borrowed_str` and `visit_string` call `visit_str`. You override only the ones you accept. 4. The required `expecting` method writes the "expected ..." half of every error message. `deserialize_any` means "tell me what you have". Only **self-describing** formats such as JSON can answer; Serde's documentation warns that relying on it limits a type to self-describing formats, ruling out Postcard and many others. A format-neutral visitor calls a specific method such as `deserialize_u64` instead. ## The cents visitor The example's `CentsVisitor` has `type Value = u64` and three methods: - `visit_u64` returns the number unchanged. - `visit_str` parses the text with `str::parse`. On failure it returns `E::invalid_value(de::Unexpected::Str(v), &self)`, which produces `invalid value: string "19.99", expected an amount in cents as a number or a digit string`. Passing `&self` reuses `expecting`, so the wording stays in one place. - `expecting` describes what is acceptable. Inputs the visitor does not accept fall through to the defaults. JSON `true` calls `visit_bool` and gets ``invalid type: boolean `true`, expected an amount in cents ...``; `-5` calls `visit_i64`, not `visit_u64`, and is rejected the same way. serde_json appends the line and column to all of them. Distinguishing **invalid type** (wrong kind of value) from **invalid value** (right kind, unacceptable content) makes the log line actionable. ## The untagged alternative The shortcut is a helper enum, `#[serde(untagged)] enum NumOrText { Num(u64), Text(String) }`, deserialized inside the `deserialize_with` function and matched afterwards. It is shorter, and it works, but it costs something: | Concern | Visitor | Untagged helper | |---|---|---| | Input handling | one pass, straight to the right method | buffers the value, then tries each variant in order | | Allocation for a string | none: `visit_str` gets a borrowed slice | `Text(String)` allocates before parsing | | Error when nothing fits | names what arrived and what was expected | `data did not match any variant of untagged enum NumOrText` | | Error when parsing fails | your `invalid_value` text | whatever the parse error says, such as `invalid digit found in string` | | Code size | about twenty lines | about eight lines | For an internal tool, the untagged helper is fine. On an external webhook, where the rejection log is the only clue you get about a sender's bug, the visitor's errors earn the extra lines. ## Practical rules - Put the function next to the struct, or in a module used with `with`, and give it a test for each accepted shape and each rejected one. - Add `serialize_with` when the output must match the input convention; otherwise the derived output writes a plain number. - Remember that `deserialize_with` replaces the field's whole deserialization: for an `Option` field, your function must handle `null` itself, and an absent key needs `#[serde(default)]`. - Keep custom code at the edge. Once the value is a `u64` inside the struct, the rest of the program never sees the sender's inconsistency. Writing a derive macro of your own is a different job, which the material on derive macros covers.
- How would you write the amount back out as a string?Add `serialize_with = "cents_as_string"` with `fn cents_as_string<S: Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error>` that calls `s.serialize_str(&v.to_string())`. Or put both functions, named `serialize` and `deserialize`, in one module and write `#[serde(with = "module")]`, which wires up both directions at once.
- Why does the visitor reject -5 even though it implements visit_u64?serde_json hands a negative integer to `visit_i64`, not `visit_u64`. The visitor does not override `visit_i64`, so the trait's default runs and returns ``invalid type: integer `-5`, expected ...`` built from `expecting`. Each data-model type has its own visit method, and you opt in method by method.
- Would this visitor work with a binary format such as Postcard?Not as written. `deserialize_any` asks the format what the next value is, which only self-describing formats like JSON can answer, and Serde's docs say relying on it rules out Postcard and many other formats. A format-neutral version calls a specific method such as `deserialize_u64`, giving up the number-or-string flexibility.
- deserialize_with requires the field type to implement Deserialize anyway.
- A Visitor must implement every visit method or it will not compile.
- serde_json calls visit_u64 for negative integers too.
- An untagged enum's error names the closest variant and the failing field.
- deserialize_any works the same with every Serde format.