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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Untagged enums let a single field accept several JSON shapes without custom parsing code.
- 2serde tries each enum variant in order and uses the first that deserializes successfully.
- 3Providing a Default lets serde fill in absent fields cleanly with #[serde(default)].
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-flexible-json-shapes-with-serde-explained-rust-d265/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.