In Rust, how do you deserialize a JSON webhook body into an `OrderEvent` struct with Serde, and what does serde's `derive` feature add?
answer
- two crates, one Cargo feature
- derive writes the trait impls
- from_str hands back a Result
- missing field vs unknown key
basics
~10 sDepend on serde with its derive feature plus serde_json, put #[derive(Serialize, Deserialize)] on OrderEvent, and call serde_json::from_str, which returns Result<OrderEvent, serde_json::Error>. Without that feature the derive macros do not exist.
solid answer
~40 sSerde splits the job in two: `#[derive(Serialize, Deserialize)]` generates impls that map `OrderEvent` onto Serde's data model, and a format crate such as `serde_json` maps that model to JSON text. The derive macros sit behind serde's `derive` Cargo feature, which is off by default, so the manifest says `serde = { version = "1", features = ["derive"] }`; without it rustc reports ``cannot find derive macro `Deserialize` in this scope``. Then `serde_json::from_str::<OrderEvent>(body)` returns a `Result`: an absent required field is an error such as ``missing field `order_id` ``, a value of the wrong JSON type is an `invalid type` error, an `Option` field that is absent or `null` becomes `None`, and keys the struct does not declare are ignored. `serde_json::to_string` goes the other way, and `serde_json::Value` holds JSON whose shape you do not know.
code
toml · 8 lines[package]
name = "webhooks"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"go deeper
Recall the two dependencies, the derive feature, and that serde_json::from_str returns a Result you handle with ? or match. Know that to_string goes the other way.
Explain the split: the derive maps the type onto Serde's data model and serde_json maps that model to JSON, which is why one derive serves every format crate.
Show the defaults that bite in production: unknown keys are dropped silently, absent Option fields become None, and the error text carries line and column for the rejection log.
Tie the defaults to contract policy: whether a service tolerates unknown webhook fields or rejects them is a choice, and Serde's lenient default is only the starting point.
## Two halves: the type and the format **Serde** is the serialisation framework almost every Rust service uses, and it is built from two independent halves that meet in the middle: - A **data structure** implements the `Serialize` and `Deserialize` traits. Those impls describe the type in terms of the **Serde data model**, a small type system of 29 types (bool, the integers, strings, byte arrays, options, sequences, maps, structs, enum variants and a few more). - A **data format** crate, such as `serde_json`, implements `Serializer` and `Deserializer`. It turns the data model into bytes and back. Because the two halves only talk through the data model, one `#[derive(Serialize, Deserialize)]` on `OrderEvent` works with JSON, TOML, bincode or any other format crate. You never write a JSON-specific impl for your type, and a format crate never needs to know your types. ## Setting up the crates The traits live in the `serde` crate, but the **derive macros** that generate them come from `serde_derive` and are re-exported by `serde` only when its `derive` Cargo feature is on. That feature is not in serde's default set (the default is just `std`), so a plain `serde = "1"` gives you the traits without the macros, and rustc stops with ``cannot find derive macro `Deserialize` in this scope``. The working manifest is: ```toml [dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" ``` `serde_json` has no `derive` feature of its own; asking for one makes Cargo refuse the manifest. How Cargo features work in general belongs to the material on Cargo features. ## Deserializing and serializing With the derive in place, the whole round trip is two calls: ```rust let event: OrderEvent = serde_json::from_str(body)?; let text = serde_json::to_string(&event)?; ``` `serde_json::from_str` is generic over the target type, so it needs to know it: either annotate the binding as above or use the turbofish, `serde_json::from_str::<OrderEvent>(body)`. It returns `Result<OrderEvent, serde_json::Error>` and reports bad input through that `Result` rather than by panicking. The error's `Display` text says what went wrong and where, for example ``missing field `order_id` at line 1 column 18``, which is exactly what you want in a log line for a rejected webhook. `to_string` writes compact JSON; `to_string_pretty` indents it. ## What the derived impl does with each field The generated `Deserialize` impl reads JSON object keys and matches them against the struct's field names. Its defaults are lenient on purpose: | JSON input for a field | Field type | Result | |---|---|---| | present with the right type | any | the value | | absent | `u64`, `String`, ... | error: ``missing field `order_id` `` | | absent or `null` | `Option<T>` | `None` | | `"42"` (a string) | `u64` | error: `invalid type: string "42", expected u64` | | a key the struct does not declare | none | silently ignored | Two consequences matter in practice: 1. **Serde does not coerce.** A number sent as a string is a type error, not a conversion. Accepting both shapes takes a custom deserializer. 2. **Unknown keys are dropped**, so a sender can add fields without breaking you. Rejecting them instead is an opt-in container attribute, `#[serde(deny_unknown_fields)]`. Serialisation is symmetric: every field is written under its Rust name, and an `Option` that is `None` is written as `null` unless an attribute tells Serde to skip it. ## Untyped JSON with `serde_json::Value` When you do not know the shape in advance, deserialize into `serde_json::Value`, an enum with the variants `Null`, `Bool`, `Number`, `String`, `Array` and `Object`. Indexing it with `v["order_id"]` returns a reference to `Value::Null` for a missing key rather than panicking, and `serde_json::from_value::<OrderEvent>(v)` converts it into a typed struct later. `Value` suits proxies, debugging dumps and pass-through fields; for data you act on, a typed struct is better, because the compiler checks every field access and malformed input fails at the boundary instead of deep in the handler. ## Mistakes that show up in review - Forgetting the `derive` feature and trying to fix the error by implementing the trait by hand. - Expecting `from_str` to reject unknown keys, or to treat a missing non-`Option` field as a default. - Calling `.unwrap()` on `from_str` in a request handler, so one malformed webhook takes down the task; propagate the error with `?` and return a 4xx instead. - Parsing everything into `Value` and then indexing by string, which gives up the type checking that makes Serde worth using.
- What does rustc report when serde's derive feature is missing, and why?rustc says ``cannot find derive macro `Deserialize` in this scope`` and notes that `Deserialize` is a trait, not a derive macro. The serde crate re-exports the macros from serde_derive only when its `derive` feature is enabled, and the default feature set is just `std`. Adding `features = ["derive"]` to the serde dependency fixes it.
- When would you parse a webhook into serde_json::Value instead of a struct?When the shape is unknown or you only forward it: a proxy, a debugging dump, an opaque metadata field. `Value` is an enum of `Null`, `Bool`, `Number`, `String`, `Array` and `Object`; indexing a missing key yields `Value::Null` instead of panicking. For anything the handler acts on, a typed struct is better, and `serde_json::from_value` converts a `Value` into one later.
- Plain serde = "1" already provides the derive macros.
- serde_json rejects JSON keys the struct does not declare by default.
- An absent Option field fails with a missing field error.
- serde_json::from_str panics on malformed JSON instead of returning a Result.
- Each format needs its own derive, so JSON and TOML need separate impls.
- serde_json quietly converts the string "42" into a u64 field.