expression
Custom field deserialization
Use a field adapter for an explicitly chosen wire type. Here a string is parsed into an unsigned integer and bad input becomes an error. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 42 true Common mistake: Assuming a JSON number will be accepted by a string-only adapter.
Formal Syntax & Structure
rust syntaxrust
#[serde(deserialize_with = "function")]Working Example
Example Snippetrust
fn main() { fn parse_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> { let text = <String as serde::Deserialize>::deserialize(d)?; text.parse().map_err(serde::de::Error::custom) } #[derive(serde::Deserialize)] struct Record { #[serde(deserialize_with = "parse_id")] id: u64 } let r: Record = serde_json::from_str(r#"{"id":"42"}"#).unwrap(); println!("{}", r.id); println!("{}", serde_json::from_str::<Record>(r#"{"id":"bad"}"#).is_err());}