Add value of a method to serde serialization output

Viewed 1235

Is there a way to add the value of a method to the serialization output of serde when the struct derives Serialize? I'm looking for something like a "virtual field".

I know I can define my own Serializer / Visitor or use serde_json::builder to get a Value, I just wanted to check first if there was any way to do this using serde_macro magic.

To be clear I want something like this:

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    bar: String,
    #[serde(call="Foo::baz")]
    baz: i32 // but this is not a real field
}

impl Foo {
    fn baz(&self) -> i32 { self.bar.len() as i32 }
}
1 Answers
Related