Sub topic 15
How Deserialize works: Deserializer and Visitor
This chapter assumes you have read the earlier chapters on the data model, the Serialize and Deserialize traits, and manual implementations. You should be comfortable with traits, generics, and lifetimes. Here you will see what happens inside a derived Deserialize and write that code yourself.
Why deserialization needs two traits
Serialization is simple to describe. A value walks over its own fields and hands each one to a Serializer. The value knows its shape, so it drives the process.
Deserialization reverses the roles. The input decides what comes next. A JSON parser that meets "high" or 5 knows which it found, but your type does not. serde solves this with two cooperating pieces:
- A Deserializer is the format side. It owns the input, such as a JSON string, and parses it.
- A Visitor is the type side. It is a small object that says which data-model values it accepts and builds your value from them.
Your Deserialize implementation connects the two. It picks a deserialize_* method on the Deserializer and passes a Visitor. The Deserializer parses the input and calls back into the visitor with what it found.
The trait signature shows the same structure:
pub trait Deserialize<'de>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>;
}The 'de lifetime is the lifetime of the input data. A visitor can borrow from the input for 'de, which is how zero-copy deserialization works.
The Visitor trait
Visitor<'de> has one required item besides the Value type: expecting. It writes a description of what the visitor accepts, and serde uses it in error messages. Every visit_* method has a default that returns an "invalid type" error built from that description. You override only the methods for data your type accepts.
| Method | Called when the format found |
|---|---|
| `visit_bool` | a boolean |
| `visit_i64`, `visit_u64`, `visit_f64` | a number |
| `visit_str` | a string that is only valid for the call |
| `visit_borrowed_str` | a string that lives for `'de` in the input |
| `visit_string` | an owned `String` |
| `visit_seq` | a sequence, given a `SeqAccess` |
| `visit_map` | a map, given a `MapAccess` |
| `visit_enum` | an enum, given an `EnumAccess` |
| `visit_none`, `visit_some`, `visit_unit` | absent value, present value, or `()` |
Some defaults forward to others, so you rarely implement every method. visit_i8, visit_i16, and visit_i32 forward to visit_i64. The unsigned variants forward to visit_u64. visit_borrowed_str and visit_string both forward to visit_str. Implementing visit_str therefore covers all three string cases, at the cost of copying if you want an owned value.
A complete visitor: accepting two input shapes
This type accepts either an integer from 0 to 255 or the strings "low" and "high". Add serde = "1" and serde_json = "1" to your dependencies. This chapter does not use the derive feature.
use serde::de::{self, Deserialize, Deserializer, Visitor};
use std::fmt;
#[derive(Debug)]
struct Level(u8);
struct LevelVisitor;
impl<'de> Visitor<'de> for LevelVisitor {
type Value = Level;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("an integer from 0 to 255 or the string \"low\" or \"high\"")
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Level, E> {
u8::try_from(v)
.map(Level)
.map_err(|_| E::invalid_value(de::Unexpected::Unsigned(v), &self))
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Level, E> {
match v {
"low" => Ok(Level(1)),
"high" => Ok(Level(9)),
_ => Err(E::unknown_variant(v, &["low", "high"])),
}
}
}
impl<'de> Deserialize<'de> for Level {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(LevelVisitor)
}
}
fn main() {
for input in ["5", "\"high\"", "300", "-1", "true", "\"mid\""] {
match serde_json::from_str::<Level>(input) {
Ok(level) => println!("{input} -> {level:?}"),
Err(e) => println!("{input} -> error: {e}"),
}
}
}The results fall into three groups:
5and"high"succeed.serde_jsonreports every non-negative integer throughvisit_u64, so one method covers all of them.300and"mid"reach your code and fail with errors you built.300givesinvalid value: integer 300, expected an integer from 0 to 255 ...."mid"givesunknown variant mid, expected low or high.-1andtruenever reach your code. The defaultvisit_i64andvisit_boolreturninvalid type: ..., expectedfollowed by yourexpectingtext.
serde_json appends a line and column to each message. The generic E: de::Error is the format's own error type, so your visitor works with every format.
Handling sequences and maps
For compound data the Deserializer passes an access object, and you pull elements out of it one at a time. This visitor builds a Point from a two-element array such as [3, 4]:
use serde::de::{self, Deserialize, Deserializer, SeqAccess, 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("an array of two integers")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Point, A::Error> {
let x = seq
.next_element()?
.ok_or_else(|| <A::Error as de::Error>::invalid_length(0, &self))?;
let y = seq
.next_element()?
.ok_or_else(|| <A::Error as de::Error>::invalid_length(1, &self))?;
Ok(Point { x, y })
}
}
impl<'de> Deserialize<'de> for Point {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_seq(PointVisitor)
}
}
fn main() {
println!("{:?}", serde_json::from_str::<Point>("[3, 4]"));
println!("{:?}", serde_json::from_str::<Point>("[3]"));
println!("{:?}", serde_json::from_str::<Point>("{\"x\": 3}"));
}next_element returns Ok(None) when the sequence ends early, and invalid_length turns that into an error. The element type is inferred from the Point fields. The first call succeeds, the second fails with invalid length 1, and the third fails with invalid type: map.
MapAccess works the same way, but you call next_key and next_value in a loop. The derive generates this loop for structs. It matches each key against the field names, stores the values, and reports missing or duplicate fields at the end.
Choosing a deserialize_* method
Each deserialize_* method is a hint about what your type expects. Two kinds of format exist:
- Self-describing formats such as JSON and TOML can tell what comes next by looking at the input.
deserialize_anyworks with them, as inLevel. - Non-self-describing formats such as bincode store no type markers. The format cannot guess, so it returns an error for
deserialize_any. You must call the specific method, such asdeserialize_u8,deserialize_str, ordeserialize_seq.
Prefer the specific method when your type has one expected shape, as Point does with deserialize_seq. Use deserialize_any only when you really accept several shapes, and know that this limits you to self-describing formats.
Borrowing and the visitor
visit_borrowed_str is the visitor-level source of the zero-copy behavior covered in the borrowing chapter. A parser calls it only when the string exists unchanged in the input, for example JSON without escape sequences. A visitor that stores &'de str must implement visit_borrowed_str. If you implement only visit_str, the default forwarding still works, but you have to copy the data.
Common mistakes
- Skipping
expecting. It is required, and a vague message makes every error from your type hard to read. - Returning
Err(E::custom(...))for type mismatches. Useinvalid_type,invalid_value,invalid_length, andunknown_variant. They produce consistent messages that name both the unexpected and the expected data. - Relying on
deserialize_anywith bincode or similar formats. It fails at runtime. The code compiles, so the problem shows up only when you switch formats. - Reaching for a visitor too early. For most cases
#[serde(deserialize_with = ...)]or#[serde(from = ...)]is shorter. Write a visitor when you need to accept several input shapes or parse a sequence or map by hand.
Exercise
In the Level example, what code runs when the input is the JSON value true, and why does the error mention what the type expects?
Show answer
The Deserializer calls visit_bool on LevelVisitor. LevelVisitor does not override it, so the default implementation runs. That default returns an invalid type error, and it builds the message from the expecting method, which is why the error ends with "expected an integer from 0 to 255 or the string "low" or "high"".
Exercise
Why does calling deserialize_any inside a Deserialize impl make the type unusable with bincode, and what should you change to fix it for a type that accepts only a u8?
Show answer
bincode is not self-describing. Its data has no type markers, so it cannot tell which visit method to call and returns an error. Change the call to deserializer.deserialize_u8(visitor), which tells the format exactly what to read.