Add method value to output Sered Serialization

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

I know that I can define my own Serializer / Visitor or use serde_json::builder to get 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 } } 
+6
source share
1 answer

Here is what I am using right now. It's still verbose, and I don't know if this is the best way to handle this, but I thought I'd add it here for the record:

 #[derive(Deserialize, Debug)] struct Foo { bar: String } impl Foo { fn baz(&self) -> i32 { self.bar.len() as i32 } } impl ::serde::Serialize for Foo { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: ::serde::Serializer { #[derive(Serialize)] struct Extended<'a> { bar: &'a String, baz: i32 } let ext = Extended { bar: &self.bar, baz: self.baz() }; Ok(try!(ext.serialize(serializer))) } } 
+3
source

All Articles