Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an additional field while serializing

Tags:

rust

serde

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?

like image 522
porton Avatar asked May 10 '26 17:05

porton


1 Answers

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

like image 74
user4815162342 Avatar answered May 12 '26 10:05

user4815162342