expression

Custom field serialization

A field adapter can encode a value differently from its ordinary type. This example writes an integer identifier as a string. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): {"id":"9001"} Common mistake: Expecting a serialization adapter to change deserialization as well.

Formal Syntax & Structure

rust syntaxrust
#[serde(serialize_with = "function")]

Working Example

Example Snippetrust
fn main() {    fn id_text<S: serde::Serializer>(id: &u64, s: S) -> Result<S::Ok, S::Error> {        s.serialize_str(&id.to_string())    }    #[derive(serde::Serialize)]    struct Record { #[serde(serialize_with = "id_text")] id: u64 }    println!("{}", serde_json::to_string(&Record { id: 9001 }).unwrap());}
Rust Reference