Sub topic 12
Custom field logic with serialize_with and deserialize_with
This chapter assumes you know how to derive Serialize and Deserialize, and that you are comfortable with generics and lifetimes in function signatures. It also assumes you have seen field attributes such as rename and default.
When attributes are not enough
Attributes like rename and default change names and fallbacks. They cannot change how a single value is written. Suppose a u32 color should appear in JSON as the string "0xff8800". You could write Serialize by hand for the whole struct. A smaller fix is to replace the logic for one field and keep the derive for the rest.
Two field attributes do this:
serialize_with = "path"names a function that writes the field.deserialize_with = "path"names a function that reads the field.
You can use either one alone, or both together.
The required signatures
The function signatures are fixed, and the compiler checks them.
For serialize_with, the function is generic over the serializer. It takes a reference to the field's type and returns Result<S::Ok, S::Error>:
fn name<S: Serializer>(value: &T, serializer: S) -> Result<S::Ok, S::Error>For deserialize_with, the function is generic over a deserializer with the 'de lifetime. It returns the field's type:
fn name<'de, D: Deserializer<'de>>(deserializer: D) -> Result<T, D::Error>A complete example
This program writes rgb as a hex string and reads it back.
use serde::{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 s = String::deserialize(deserializer)?;
let digits = s.strip_prefix("0x").unwrap_or(&s);
u32::from_str_radix(digits, 16).map_err(serde::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 json = serde_json::to_string(&Color { rgb: 0xff8800 })?;
println!("{json}"); // {"rgb":"0xff8800"}
let back: Color = serde_json::from_str(&json)?;
println!("{back:?}"); // Color { rgb: 16746496 }
let bad = serde_json::from_str::<Color>(r#"{"rgb":"zz"}"#);
println!("{}", bad.unwrap_err());
Ok(())
}Two details matter here.
as_hexhands a string to the serializer. It never mentions JSON, so the same function works with any format crate.from_hexfirst reads aStringby callingString::deserialize(deserializer). It then parses the text. The parse error is turned into a serde error withserde::de::Error::custom. That error carries your message and, withserde_json, the line and column.
Grouping both directions with `with`
If a pair of functions belongs together, put them in a module and use with = "module". Serde then calls module::serialize and module::deserialize.
mod hex_u32 {
use serde::{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 s = String::deserialize(deserializer)?;
let digits = s.strip_prefix("0x").unwrap_or(&s);
u32::from_str_radix(digits, 16).map_err(serde::de::Error::custom)
}
}You would then write #[serde(with = "hex_u32")] on the field.
Common mistakes
- Wrong argument type. The function receives
&TwhereTis the field's type. For anOption<u32>field, the parameter is&Option<u32>, not&u32. - Missing field with
deserialize_with. The attribute does not make a field optional. If the key is absent, deserialization fails unless you also add#[serde(default)]. - Path as a string. The function name goes inside quotes, for example
"as_hex". For a function in another module, use the full path, such as"crate::util::as_hex".
Exercise
A struct has the field timeout: Option<u32> marked with #[serde(serialize_with = "ser_timeout")]. What must the first parameter of ser_timeout look like?
Show answer
It must be &Option<u32>. The function receives a reference to the field's full type, so the Option is included, and the function decides how to write both Some and None. Its second parameter is a generic S: Serializer.