Sub topic 15
How Deserialize works: Deserializer and Visitor
This chapter assumes you have read the earlier chapters on the serde data model and the Serialize and Deserialize traits. You should also be comfortable with Rust traits, generics, and lifetimes.
You rarely write this code. The derive macro generates it for you. Reading it once explains the lifetime in Deserialize<'de> and where error messages like "invalid type: integer, expected a string" come from.
Two roles
Deserializing involves two cooperating parts:
- A Deserializer is the format side.
serde_jsonprovides one that reads JSON text. It knows what is in the input, such as a string, a number, or a map. - A Visitor is the type side. It says which kinds of values it can accept and builds your Rust value from them.
Deserialize::deserialize connects them. Your type picks a deserialize_* method on the deserializer and passes in a visitor. The deserializer reads the input and calls the matching visit_* method on that visitor.
A complete example
This type reads a Point from a string such as "3,4".
use serde::de::{self, Deserialize, Deserializer, Visitor};
use std::fmt;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
struct PointVisitor;
impl<'de> Visitor<'de> for PointVisitor {
type Value = Point;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a string like \"3,4\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Point, E> {
let (x, y) = v
.split_once(',')
.ok_or_else(|| E::custom("missing comma"))?;
let x: i32 = x.trim().parse().map_err(E::custom)?;
let y: i32 = y.trim().parse().map_err(E::custom)?;
Ok(Point { x, y })
}
}
impl<'de> Deserialize<'de> for Point {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_str(PointVisitor)
}
}
fn main() -> Result<(), serde_json::Error> {
let p: Point = serde_json::from_str(r#""3,4""#)?;
println!("{p:?}");
let err = serde_json::from_str::<Point>("42").unwrap_err();
println!("{err}");
Ok(())
}The first call prints Point { x: 3, y: 4 }. The second fails because the input is a number, not a string. The message reads like invalid type: integer 42, expected a string like "3,4" at line 1 column 2.
What each piece does
type Valueis what the visitor produces.expectingdescribes the accepted input. Serde inserts this text into the "expected ..." part of error messages.visit_strhandles string input. The default implementations of every othervisit_*method return an "invalid type" error built fromexpecting. That is why the number42was rejected without extra code.E::custombuilds an error in whatever type the format uses, so the visitor stays independent of JSON.
Why the 'de lifetime exists
The 'de lifetime is the lifetime of the input data. A visitor can also implement visit_borrowed_str, which receives a &'de str pointing directly into the input. This is the mechanism behind zero-copy deserialization with #[serde(borrow)]. Plain visit_str gives a string that is only valid during the call, so you must copy it if you want to keep it.
Self-describing and hint-based formats
deserialize_str is a hint. JSON can look at the input and see what is there, so it can call any visit_* method. Compact binary formats cannot do this, because the bytes carry no type information. They rely on your type's hint and read exactly what it asks for. This is why a type should call the most accurate deserialize_* method, and why deserialize_any fails on such formats.
Exercise
In the example, why does deserializing the JSON number 42 into Point return an error without any code that checks for numbers?
Show answer
Point calls deserializestr, so the deserializer calls a visit* method for the integer. PointVisitor implements only visitstr. The default visiti64 and visit_u64 methods return an invalid type error that uses the text from expecting.