Sub topic 2
The serde data model as a common middle layer
This chapter assumes you can read Rust structs, enums, traits and generics, and that you have already derived Serialize on a type and called serde_json::to_string. You also need to be comfortable with JSON. The chapter explains the layer that sits between your types and a format such as JSON. Knowing it makes later behavior predictable, such as why a newtype becomes a bare number or why a Vec<u8> prints as an array.
The problem a middle layer solves
Suppose you have M Rust types and N formats (JSON, TOML, YAML, MessagePack, bincode). Without a shared layer, each type would need code for each format, which is M × N pieces. Serde avoids this with a fixed vocabulary called the data model. It is a set of 29 kinds of value that every Rust type is described in terms of and every format knows how to read and write.
- A type implements
Serializeonce. That implementation describes the type using data model kinds. - A format crate implements
SerializerandDeserializeronce. That implementation turns data model kinds into bytes or text, and back.
The work becomes M + N, and any type works with any format. The data model is not a Rust type or a value you can hold. It is the set of method calls that cross the boundary between a type and a format.
The 29 kinds
The data model has these kinds:
- Primitives (14):
bool,i8,i16,i32,i64,i128,u8,u16,u32,u64,u128,f32,f64,char. - string: UTF-8 text. It may be owned, borrowed, or valid only for a moment.
- byte array: raw bytes, written
[u8]. - option: either nothing or some value.
- unit: the anonymous value with no data,
(). - unit struct: a named value with no data, such as
struct Marker;. - unit variant: an enum variant with no data, such as
Shape::Empty. - newtype struct: a named wrapper around exactly one value, such as
struct Meters(f64);. - newtype variant: an enum variant wrapping one value, such as
Shape::Circle(f64). - seq: a variable-length sequence, such as
Vec<T>. The length may be unknown up front. - tuple: a fixed-length sequence where the length is known at compile time and needs no prefix.
- tuple struct: a named tuple, such as
struct Pair(i32, i32);. - tuple variant: an enum variant holding a tuple, such as
Shape::Rect(f64, f64). - map: a variable-size collection of key-value pairs, such as
HashMap<K, V>. - struct: a fixed set of named fields, where keys are static strings.
- struct variant: an enum variant with named fields, such as
Shape::Square { side: f64 }.
Notice what is missing. Vec, HashMap, String, Box, Rc and PathBuf are not data model kinds. They are Rust types whose Serialize implementations pick a kind: Vec<T> is a seq, HashMap<K, V> is a map, String is a string, and Box<T> simply serializes the T inside. This is why a format crate never needs to know about your types.
Seeing the mapping
The program below serializes one value of many kinds to JSON, so you can see what each kind turns into. It needs serde with the derive feature and serde_json.
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize)]
struct Meters(f64);
#[derive(Serialize)]
struct Marker;
#[derive(Serialize)]
struct Pair(i32, i32);
#[derive(Serialize)]
struct Point {
x: i32,
y: i32,
}
#[derive(Serialize)]
enum Shape {
Empty,
Circle(f64),
Rect(f64, f64),
Square { side: f64 },
}
fn show<T: Serialize>(label: &str, value: &T) -> Result<(), serde_json::Error> {
println!("{label:<16}{}", serde_json::to_string(value)?);
Ok(())
}
fn main() -> Result<(), serde_json::Error> {
show("newtype struct", &Meters(1.5))?;
show("unit struct", &Marker)?;
show("tuple struct", &Pair(1, 2))?;
show("struct", &Point { x: 1, y: 2 })?;
show("unit variant", &Shape::Empty)?;
show("newtype variant", &Shape::Circle(1.0))?;
show("tuple variant", &Shape::Rect(2.0, 3.0))?;
show("struct variant", &Shape::Square { side: 4.0 })?;
show("tuple", &(1, "a", true))?;
show("some", &Some(7))?;
show("none", &None::<i32>)?;
let mut map = BTreeMap::new();
map.insert(1, "one");
map.insert(2, "two");
show("map", &map)?;
show("Vec<u8>", &vec![1u8, 2, 3])?;
Ok(())
}The output is:
newtype struct 1.5
unit struct null
tuple struct [1,2]
struct {"x":1,"y":2}
unit variant "Empty"
newtype variant {"Circle":1.0}
tuple variant {"Rect":[2.0,3.0]}
struct variant {"Square":{"side":4.0}}
tuple [1,"a",true]
some 7
none null
map {"1":"one","2":"two"}
Vec<u8> [1,2,3]Each line is the JSON format's choice for one data model kind. The table collects them.
| Data model kind | Typical Rust source | JSON output |
|---|---|---|
| newtype struct | `Meters(1.5)` | the inner value, `1.5` |
| unit, unit struct | `()`, `Marker` | `null` |
| tuple, tuple struct, seq | `Pair(1, 2)`, `Vec<T>` | array |
| struct, map | `Point { .. }`, `BTreeMap` | object |
| option | `Some(7)`, `None` | the value, or `null` |
| unit variant | `Shape::Empty` | the variant name as a string |
| newtype, tuple, struct variant | `Shape::Circle(1.0)` | an object with the variant name as its only key |
Why the model is not just "JSON"
Several details show that the model is more precise than any one format.
Formats decide how to spell each kind. JSON has no separate notion of a newtype, so it writes the inner value. A binary format might write the same newtype with no wrapper at all. A format may also collapse kinds: JSON writes a unit and a None both as null. That makes Option<()> ambiguous in JSON, which is a limit of JSON and not of serde.
Struct and map are different kinds. A struct has field names known at compile time, passed as &'static str. A map has keys that are computed values. JSON writes both as objects, but a compact format like bincode drops struct field names entirely and relies on field order. That works only because the struct kind promises a fixed set of fields.
Variants carry a name and an index. When a type serializes an enum variant, it passes the enum name, the variant's index, and the variant name. Text formats usually use the name. Compact binary formats often use the index. Reordering the variants in your enum can therefore change binary output but not JSON output.
Map keys have format limits. The data model lets a map key be any kind, but a format may refuse some. JSON converts integer keys to strings, as the "1" and "2" above show. It returns an error for a key like a struct or a sequence.
Bytes and sequences of u8 are different. The model has a byte array kind, but Vec<u8> serializes as a seq of integers, so JSON shows [1,2,3]. A format that has a compact byte string type only gets it if the type asks for the byte array kind. The serde_bytes crate provides wrappers that do this.
The same model on the way back
Deserialization uses the same vocabulary in the other direction. A Deserialize implementation tells the Deserializer which kind it expects, for example "I want a struct with fields x and y". The format reads its input and reports what it found in data model terms.
Two consequences follow.
- Self-describing formats can guess. JSON text shows whether the next value is a number, a string, or an array, so the deserializer can answer a request like "give me whatever is here". This is what
serde_json::Valueand untagged enums rely on. Formats like bincode are not self-describing. They cannot answer that question because the bytes carry no type markers. - Types are checked against the kinds. If you ask for a
u8and the input holds300, or a string where a number should be, the deserializer reports a mismatch between expected and found kinds. Later chapters cover reading these errors.
Practical rules that follow
- Design your Rust types for your own program first. Serde will choose a kind for each one.
- When output surprises you, find which kind the type uses and how your format spells that kind. The table above covers most cases.
- Expect that a type which works with JSON may fail with another format. TOML, for instance, cannot represent a bare top-level value like
1.5, and it requires keys to be strings. - When the default kind is wrong for a field, change the kind with an attribute or a custom function. You will see both in later chapters.
Exercise
Given struct Id(u64); and struct Wrapper { id: Id, tags: (String, String) }, which data model kinds does Wrapper use, and what does serde_json print for Wrapper { id: Id(5), tags: ("a".into(), "b".into()) }?
Show answer
Wrapper is a struct with two fields. id is a newtype struct around a u64. tags is a tuple of two strings. JSON writes the newtype as its inner value and the tuple as an array, so the output is {"id":5,"tags":["a","b"]}.
Exercise
Why can serde support many formats without every type knowing about each one?
Show answer
Types describe themselves only in terms of the 29 data model kinds through Serialize and Deserialize. Formats implement Serializer and Deserializer in terms of the same kinds. Because both sides use the shared vocabulary, one type implementation works with every format, and the work grows as M + N instead of M × N.