Sub topic 12
Custom field logic with serialize_with and deserialize_with
This chapter assumes you can derive Serialize and Deserialize, use serde_json to round-trip a struct, and read basic serde attributes such as rename and default. It also assumes you are comfortable with generic functions and trait bounds in Rust.
When an attribute is not enough
Attributes such as rename, default, and skip_serializing_if cover many cases. Sometimes one field needs behavior that no built-in attribute provides. Examples:
- A
u32color that must appear in JSON as the string"0xff8800". - A string that is empty in the input but should become
Nonein your struct. - A timestamp stored as an integer that must be written in a different unit.
You could implement Serialize for the whole struct by hand, but that means rewriting every other field too. The serialize_with and deserialize_with attributes avoid this. You point one field at your own function. The derive macro still generates everything else.
The function signatures
The functions must have exact shapes, because the derived code calls them directly.
| Attribute | Function shape |
|---|---|
| `serialize_with = "path"` | `fn<S: Serializer>(&T, S) -> Result<S::Ok, S::Error>` |
| `deserialize_with = "path"` | `fn<'de, D: Deserializer<'de>>(D) -> Result<T, D::Error>` |
T is the field's type. It may be a concrete type or a generic one. The string is a Rust path, so "as_hex", "self::as_hex", and "crate::codec::as_hex" all work.
Your function receives the serializer or deserializer itself, not a finished value. It must hand a value to the serializer, or pull a value out of the deserializer, using the serde data model.
Serializing a field with serialize_with
The simplest serializer function converts the value to a type serde already knows how to write, then calls the matching serialize_* method.
use serde::{Serialize, Serializer};
fn as_hex<S: Serializer>(value: &u32, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{value:#x}"))
}
#[derive(Serialize)]
struct Color {
#[serde(serialize_with = "as_hex")]
rgb: u32,
name: String,
}
fn main() -> Result<(), serde_json::Error> {
let color = Color {
rgb: 0xff8800,
name: "orange".to_string(),
};
println!("{}", serde_json::to_string(&color)?);
// {"rgb":"0xff8800","name":"orange"}
Ok(())
}The name field is serialized by the normal derived path. Only rgb goes through as_hex.
Deserializing a field with deserialize_with
The usual pattern for the reverse direction is to deserialize into an intermediate type that the format can supply, such as String. Then convert that value, and report failure through the deserializer's error type.
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
fn as_hex<S: Serializer>(value: &u32, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{value:#x}"))
}
fn from_hex<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
let text = String::deserialize(deserializer)?;
let digits = text.strip_prefix("0x").unwrap_or(&text);
u32::from_str_radix(digits, 16).map_err(de::Error::custom)
}
#[derive(Debug, Serialize, Deserialize)]
struct Color {
#[serde(serialize_with = "as_hex", deserialize_with = "from_hex")]
rgb: u32,
}
fn main() -> Result<(), serde_json::Error> {
let color: Color = serde_json::from_str(r#"{"rgb":"0xff8800"}"#)?;
println!("{color:?}"); // Color { rgb: 16746496 }
println!("{}", serde_json::to_string(&color)?); // {"rgb":"0xff8800"}
let bad = serde_json::from_str::<Color>(r#"{"rgb":"0xzz"}"#);
println!("{}", bad.unwrap_err());
// invalid digit found in string at line 1 column 14
Ok(())
}Three details matter here:
String::deserialize(deserializer)works becauseStringimplementsDeserialize. You are reusing existing implementations instead of writing a visitor.de::Error::custombuilds an error of whatever type the deserializer uses. It accepts any value that implementsDisplay.serde_jsonappends the line and column to custom errors.- The
'delifetime must appear in the signature, even though this function does not borrow anything.
Bundling both directions with `with`
If a field needs both functions, the with attribute is shorter. It names a module. Serde looks for serialize and deserialize functions inside it.
use serde::{Deserialize, Serialize};
mod hex {
use serde::{de, Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &u32, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{value:#x}"))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
let text = String::deserialize(deserializer)?;
let digits = text.strip_prefix("0x").unwrap_or(&text);
u32::from_str_radix(digits, 16).map_err(de::Error::custom)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct Color {
#[serde(with = "hex")]
rgb: u32,
}
fn main() -> Result<(), serde_json::Error> {
let color: Color = serde_json::from_str(r#"{"rgb":"0x10"}"#)?;
println!("{color:?}"); // Color { rgb: 16 }
println!("{}", serde_json::to_string(&color)?); // {"rgb":"0x10"}
Ok(())
}with = "hex" is equivalent to serialize_with = "hex::serialize" plus deserialize_with = "hex::deserialize". A module like this is easy to reuse across many structs.
How the derived code uses your function
The derive macro does not call your function directly. It wraps the field in a small private adapter type that implements Serialize or Deserialize by delegating to your function. That adapter then goes through the normal field path.
This explains why your function must be generic over the serializer. The same derived code works with JSON, TOML, or any other format, so your function must not assume one.
Option fields and missing values
Two behaviors surprise people when a field is an Option.
Serializing. The function receives &Option<T>, not &T. You must handle both cases yourself and call serialize_some or serialize_none.
Deserializing. With no deserialize_with, serde treats a missing Option field as None. Once you add deserialize_with, that special case no longer applies, and a missing key produces a missing field error. Add #[serde(default)] to restore the behavior.
use serde::{Deserialize, Deserializer};
fn empty_as_none<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
let value = Option::<String>::deserialize(deserializer)?;
Ok(value.filter(|text| !text.is_empty()))
}
#[derive(Debug, Deserialize)]
struct Profile {
name: String,
#[serde(default, deserialize_with = "empty_as_none")]
nickname: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
for input in [
r#"{"name":"Ada","nickname":"Countess"}"#,
r#"{"name":"Ada","nickname":""}"#,
r#"{"name":"Ada","nickname":null}"#,
r#"{"name":"Ada"}"#,
] {
let profile: Profile = serde_json::from_str(input)?;
println!("{profile:?}");
}
Ok(())
}The first input gives Some("Countess"). The other three all give None. Delete default from the attribute and the last input fails with missing field nickname.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `mismatched types` pointing at the derive | The function's `T` does not match the field type, for example `&u32` for an `Option<u32>` field | Change the function signature to the field's exact type |
| `missing field` on an `Option` | `deserialize_with` disables the implicit `None` for missing keys | Add `#[serde(default)]` |
| `cannot find function` | The path string is relative to the wrong module | Use `self::`, `super::`, or `crate::` explicitly |
| Function compiles alone but the derive fails | The signature lacks `'de` or the right bounds | Copy the shapes from the table above |
| `with` rejects a `Vec<u32>` field | The module handles `u32`, not the collection | Write a module for `Vec<u32>`, or wrap the element type |
Choosing between the options
- Use a built-in attribute when one exists. It is shorter and well tested.
- Use
serialize_withordeserialize_withwhen one direction needs custom logic. - Use
withwhen both directions belong together, or when you want a reusable module. - Implement the trait by hand when the whole type's shape is unusual, not just one field.
Exercise
A struct has the field timeout: Duration. In JSON it should be a whole number of seconds, such as {"timeout":30}. Write the attribute and the two functions needed to serialize and deserialize it. What error type should the deserialize function use for a failed conversion, and what happens if a client sends a negative number?
Show answer
Use #[serde(with = "secs")] on the field, with a module secs containing pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_u64(value.as_secs()) } and pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> { Ok(Duration::from_secs(u64::deserialize(deserializer)?)) }. Conversion failures go through D::Error, for example de::Error::custom(...). Here the only failure source is u64::deserialize, which already returns a D::Error. A negative number such as -5 cannot be parsed as u64, so deserialization fails with an invalid type error, and the struct is never built.
Exercise
You add #[serde(deserialize_with = "empty_as_none")] to an Option<String> field, and inputs that omit the key now fail. Why, and what is the one-attribute fix?
Show answer
Serde only fills in None for a missing Option field when it generates the default deserialization for that field. Once deserialize_with replaces it, a missing key is reported as missing field. Adding #[serde(default)] to the same field makes serde use Default::default(), which is None, when the key is absent.