In Serde serializers, how to add an additional field:
#[derive(Serialize)]
struct X {
a: u32,
b: u32,
c: u32,
}
I want to add to JSON serialization field d with value "qwe". How without writing completely a serializer for X from scratch?
Assuming that you don't mind that the field d exists, but you just don't want it taking space in your struct, you can make it zero-sized and use the serialize_with attribute to emit the desired data when serializing:
#[derive(Serialize)]
struct X {
a: u32,
b: u32,
c: u32,
#[serde(serialize_with = "emit_qwe")]
d: (),
}
fn emit_qwe<S: Serializer>(_: &(), s: S) -> Result<S::Ok, S::Error> {
s.serialize_str("qwe")
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With