Sub topic 3
The Serialize and Deserialize traits
This chapter assumes you know Rust traits, generics, and lifetimes, and that you have read the previous chapter on the serde data model. Here you will see what the two traits look like, why their signatures are shaped the way they are, and how to use them as bounds in your own code.
Two traits, one job each
Everything serde does with your types goes through two traits.
Serializeturns a value into a sequence of calls on a serializer.Deserializebuilds a value by asking a deserializer for data.
The serializer and deserializer belong to a format crate such as serde_json. Your type never mentions JSON. It only speaks the data model, and the format crate maps the data model onto its own syntax.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"The Serialize trait
Here is the trait, slightly simplified from the serde source.
pub trait Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer;
}Four details matter.
- The method takes
&self. Serializing never consumes or mutates the value. - The method is generic over the serializer
S. The compiler generates one copy of your serialization code per format, with no dynamic dispatch. - The serializer is passed by value. Each serializer value is used once, and it is consumed by exactly one
serialize_*call. S::OkandS::Errorare associated types chosen by the format. Forserde_json::to_string, the error isserde_json::Error. A serializer that builds aserde_json::ValueusesValueas itsOktype.
Your implementation never inspects S. It calls one method such as serialize_str, serialize_u32, or serialize_struct, and returns whatever that method returns.
The Deserialize trait
The deserialization side has a lifetime parameter.
pub trait Deserialize<'de>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>;
}Compare it with Serialize:
- There is no
self. Deserialization is an associated function that creates a value, so the trait requiresSized. - The
'delifetime is the lifetime of the input data. A type may borrow from the input for'de, for example a&'de strfield that points into the original JSON text. - The deserializer is generic and passed by value, as on the serialize side.
Deserialize and DeserializeOwned
Many APIs cannot guarantee that the input outlives the result. A reader, such as a file or a socket, produces data that is gone after parsing. For those, serde provides a shorthand.
pub trait DeserializeOwned: for<'de> Deserialize<'de> {}T: DeserializeOwned means that T can be deserialized from input of any lifetime, so it cannot borrow from the input.
| Bound | Can borrow from input | Typical use |
|---|---|---|
| `T: Deserialize<'de>` | Yes | `serde_json::from_str`, `from_slice` |
| `T: DeserializeOwned` | No | `serde_json::from_reader`, generic helpers that drop the input |
The derive macro handles lifetimes for you. A struct with only owned fields, such as String and Vec<u8>, implements Deserialize<'de> for every 'de, which makes it DeserializeOwned. A struct with a &'a str field implements Deserialize<'de> only where 'de: 'a, so it is not DeserializeOwned.
How the pieces connect
The diagram shows both directions. Your type talks only to the trait objects of the data model, and the format crate talks only to bytes.
Calling serde_json::to_string(&value) constructs the serializer and calls value.serialize(...) for you. Calling serde_json::from_str::<T>(text) builds the deserializer and calls T::deserialize(...).
Types that already implement the traits
Serde implements both traits for most of the standard library:
- All integer and float types,
bool,char,String, and(). Option<T>,Vec<T>, arrays, tuples,HashMap<K, V>,BTreeMap<K, V>,Box<T>, andCow<'a, T>.- References:
&TisSerializewheneverTis. A reference is notDeserializein general. Only&strand&[u8]are, because they can borrow directly from the input.
Containers are serializable when their contents are. A Vec<Option<String>> works because String, Option<T>, and Vec<T> each implement the traits. This composition is why a derived struct only needs every field type to implement the trait.
Using the traits as bounds
You rarely call serialize or deserialize yourself. You use the traits as bounds in generic code.
use serde::de::DeserializeOwned;
use serde::Serialize;
fn roundtrip<T>(value: &T) -> Result<T, serde_json::Error>
where
T: Serialize + DeserializeOwned,
{
let text = serde_json::to_string(value)?;
serde_json::from_str(&text)
}
fn main() -> Result<(), serde_json::Error> {
let input = vec![Some("a".to_string()), None];
let output = roundtrip(&input)?;
println!("{output:?}"); // [Some("a"), None]
Ok(())
}DeserializeOwned is the right bound here. The function returns T after the local string text is dropped, so T must not borrow from it. If you wrote T: Deserialize<'de> with a fresh lifetime, the compiler would reject the function because text does not live long enough.
Implementing the traits by delegation
You can implement the traits by hand without touching the data model. The simplest case is a newtype that should look like the type it wraps. Delegate to the inner type.
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Debug)]
struct Celsius(f64);
impl Serialize for Celsius {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Celsius {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
f64::deserialize(deserializer).map(Celsius)
}
}
fn main() -> Result<(), serde_json::Error> {
let json = serde_json::to_string(&Celsius(21.5))?;
println!("{json}"); // 21.5
let back: Celsius = serde_json::from_str("-4.0")?;
println!("{back:?}"); // Celsius(-4.0)
Ok(())
}The wrapper does not appear in the output at all. Celsius serializes as a bare number because it hands the serializer straight to f64. The derive macro gives the same result for a newtype struct in JSON, but writing it out shows the mechanism: each implementation forwards the generic serializer or deserializer to another implementation.
Borrowing through the lifetime
The 'de parameter earns its place when a field is a reference.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Borrowed<'a> {
name: &'a str,
}
fn main() -> Result<(), serde_json::Error> {
let input = String::from(r#"{"name":"Ada"}"#);
let parsed: Borrowed = serde_json::from_str(&input)?;
println!("{parsed:?}"); // Borrowed { name: "Ada" }
Ok(())
}parsed.name points into input. No new String is allocated. The value cannot outlive input, and the borrow checker enforces that.
Limits of the trait design
- Not object safe. Both traits have generic methods, so
Box<dyn Serialize>does not compile. Theerased-serdecrate exists for cases that need trait objects, such as plugin systems. - One implementation per type. A type has one
Serializeimplementation, so you cannot define two JSON shapes for the same type by implementing the trait twice. Use attributes, wrapper types, orserialize_withfor variants. - Orphan rule. You cannot implement
Serializefor a type from another crate. Wrap it in a newtype or useserialize_withon the field. - Format-neutral by design. Your implementation must not assume JSON. For example, a
u64can be too large for some formats, and a byte sequence might be text in one format and binary in another. Each format decides.
Exercise
A helper reads a config from a file with serde_json::from_reader and is declared as fn load<T: Deserialize<'static>>(path: &str) -> T. Why is DeserializeOwned the better bound, and what kind of field would stop a type from satisfying it?
Show answer
from_reader reads into a temporary buffer, so the parsed value cannot borrow from the input. DeserializeOwned means for<'de> Deserialize<'de>, which states exactly that. A &'static bound would demand input that lives forever. A borrowed field such as &'a str would stop a type from satisfying DeserializeOwned, because it can only be deserialized when the input outlives it.
Exercise
Write the body of Serialize::serialize for struct UserId(u32) so that it serializes as a bare integer, using delegation.
Show answer
self.0.serialize(serializer). The u32 implementation calls serializer.serialize_u32, so the output is the plain number, for example 7 in JSON.