Sub topic 13
Writing a Serialize implementation by hand
This chapter assumes you know Rust traits and generics and have used #[derive(Serialize)] with serde_json. You should also know how the serde data model separates your types from formats. Add serde = { version = "1", features = ["derive"] } and serde_json = "1" to Cargo.toml.
When the derive is not enough
The derive covers most types. A manual implementation helps when the output shape differs from the Rust shape and attributes cannot express it. Examples are a type that stores one value but emits a string, or a struct that emits computed fields. For a single field, try serialize_with first. Write the whole trait only when the type itself needs different treatment.
The shape of the trait
Serialize has one method. It receives a generic Serializer, which is the format side of the data model. Your job is to call the right method on it.
pub trait Serialize {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
}You never write JSON here. You describe your value in data model terms (a struct, a string, a sequence), and the format decides how to write it.
A struct by hand
This implementation matches what the derive would produce for a two-field struct.
use serde::ser::{Serialize, SerializeStruct, Serializer};
struct Point {
x: i32,
y: i32,
}
impl Serialize for Point {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("Point", 2)?;
state.serialize_field("x", &self.x)?;
state.serialize_field("y", &self.y)?;
state.end()
}
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Point { x: 3, y: 4 })?); // {"x":3,"y":4}
Ok(())
}The steps are:
serialize_structtakes the struct name and the number of fields. It returns a helper object (SerializeStruct).serialize_fieldis called once per field, with a key and a reference to the value. The value only has to implementSerialize, so nested types work.endfinishes the struct and returns the result.
Each call returns a Result, so use ? on every one.
Choosing the right method
The Serializer trait has one entry point per data model type. Pick the one that matches what you want the output to be.
| Goal | Method |
|---|---|
| A single string | `serialize_str` |
| A number | `serialize_i32`, `serialize_u64`, `serialize_f64`, and so on |
| A list | `serialize_seq`, then `serialize_element` and `end` |
| A map with dynamic keys | `serialize_map`, then `serialize_entry` and `end` |
| A named-field record | `serialize_struct`, as above |
A type that writes a string
A common case is a wrapper that emits one primitive. This one stores seconds and writes a readable string.
use serde::{Serialize, Serializer};
struct Duration(u64);
impl Serialize for Duration {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{}s", self.0))
}
}
#[derive(Serialize)]
struct Job {
name: String,
timeout: Duration,
}
fn main() -> Result<(), serde_json::Error> {
let job = Job { name: "build".to_string(), timeout: Duration(30) };
println!("{}", serde_json::to_string(&job)?); // {"name":"build","timeout":"30s"}
Ok(())
}The derived Job works unchanged because Duration now implements Serialize. The same type would serialize to a string in TOML or any other format as well.
Diagram of the call flow
Common mistakes
- Wrong field count. The length passed to
serialize_structis a hint. Some formats rely on it, so keep it equal to the number of fields you write. - Forgetting
end. The output is incomplete without it, and the compiler warns about the unused value. - Serializing in a format-specific way. Do not build JSON strings by hand. Go through the
Serializerso your type works with every format.
Exercise
Implement Serialize by hand for struct Rgb(u8, u8, u8) so that Rgb(255, 136, 0) serializes to the JSON string "#ff8800". Which Serializer method do you call?
Show answer
Call serialize_str with a formatted string:
impl Serialize for Rgb {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2))
}
}
The {:02x} format pads each byte to two lowercase hex digits, so 255, 136, 0 gives "ff", "88", "00".