rust 40 lines · 6 steps

Parsing flexible JSON shapes with serde

How serde's untagged enums let one Rust type absorb multiple JSON representations of the same field.

Explained by highlit
1use serde::Deserialize;
2 
3#[derive(Debug, Deserialize)]
4#[serde(untagged)]
5enum StringOrNumber {
6 Number(f64),
7 Text(String),
8}
9 
10#[derive(Debug, Deserialize)]
11#[serde(untagged)]
12enum Id {
13 Numeric(u64),
14 Uuid(String),
15}
16 
17#[derive(Debug, Deserialize)]
18#[serde(untagged)]
19enum Recipient {
20 Single(String),
21 Many(Vec<String>),
22}
23 
24#[derive(Debug, Deserialize)]
25struct Notification {
26 id: Id,
27 to: Recipient,
28 #[serde(default)]
29 priority: StringOrNumber,
30}
31 
32impl Default for StringOrNumber {
33 fn default() -> Self {
34 StringOrNumber::Number(0.0)
35 }
36}
37 
38fn parse_notification(raw: &str) -> Result<Notification, serde_json::Error> {
39 serde_json::from_str(raw)
40}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Untagged enums let a single field accept several JSON shapes without custom parsing code.
  2. 2serde tries each enum variant in order and uses the first that deserializes successfully.
  3. 3Providing a Default lets serde fill in absent fields cleanly with #[serde(default)].

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing flexible JSON shapes with serde — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code