Sub topic 3
Reading and Handling Serde Errors
Prerequisites: Rust structs, traits, lifetimes, Result, the ? operator, Cargo, and basic JSON.
Reading and handling serde errors
Serde reports failures through Result<T, E>. Serialization errors often come from the output format or a custom serializer. Deserialization errors usually identify the unexpected value, field, or location.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct User {
id: u32,
}
fn main() {
match serde_json::from_str::<User>(r#"{"id":"wrong"}"#) {
Ok(user) => println!("{user:?}"),
Err(error) => eprintln!("invalid user: {error}"),
}
}Use ? when the caller should handle the error. Add context at application boundaries so the original error remains useful.
Swapping formats without changing your types
Serialize and Deserialize describe a format-independent data model. Format crates provide the conversion layer. The same type can work with JSON and TOML:
let user: User = toml::from_str(input)?;
let json = serde_json::to_string(&user)?;The attributes on User generally apply to both formats, although each format has its own syntax and limitations.
Working with untyped JSON using `Value`
Use serde_json::Value when the shape is unknown or only part of the document matters.
let document: serde_json::Value = serde_json::from_str(input)?;
let name = document["user"]["name"].as_str();Typed structs provide validation and clearer contracts. Value provides flexibility but moves more checks into runtime code.
Custom field logic
Use serialize_with or deserialize_with for one field whose representation differs from its Rust type. The helper function must use Serde’s Serializer or Deserializer traits.
use serde::{Serialize, Serializer};
fn hex<S: Serializer>(value: &u32, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&format!("{value:#x}"))
}
#[derive(Serialize)]
struct Color {
#[serde(serialize_with = "hex")]
rgb: u32,
}Writing a `Serialize` implementation by hand
Manual implementations are useful when the complete output shape is computed dynamically. Call methods such as serialize_struct, serialize_field, and end. Prefer derive macros when attributes can express the same behavior.
Zero-copy deserialization with borrowed data
A borrowed field can reference the input buffer instead of allocating a new String.
#[derive(serde::Deserialize)]
struct Record<'a> {
#[serde(borrow)]
name: std::borrow::Cow<'a, str>,
}Borrowing requires the input to outlive the result. Escaped strings may still require allocation.
How `Deserialize` works
A format-specific Deserializer reads tokens and passes them to a Visitor. The visitor constructs the requested Rust type. This separation lets one type support many formats.
Exercise
Which type should you choose when the JSON shape is fixed and should be validated?
Show answer
Define a Rust struct or enum and derive Deserialize; use Value only when the shape is genuinely dynamic.