1

Some brief context: we're storing uuids in our database; these function as ids. We'd like to present these to various http clients as base62 encoded representations. Ideally we wouldn't have to remember to do this every time we encode a struct. It's worth noting that we're also leveraging sqlx and lean on structs via query_as!. For example:

#[derive(Debug, Deserialize, FromRow, Serialize)]
pub struct Widget {
    pub id: Uuid,
    pub name: String,
}

And then later:

let widget = query_as!(Widget, r#"select * from widgets where id = $1"#, id).fetch_one(db_conn).await?;

Ideally we'd like to leverage this same struct to send data to the client and likewise when pulling data off the wire. We'd also like to convert the id when doing so (from a base62 encoding to uuid when receiving and from uuid to base62 encoding when sending).

How can we control the behavior of JSON serialization and deserialization specifically while continuing to leverage these structs?

dtolnay
  • 9,621
  • 5
  • 41
  • 62
maxcountryman
  • 1,562
  • 1
  • 24
  • 51
  • https://serde.rs/field-attrs.html#with with this attribute you can alter how individual fields are de/serialized. You need to write a function which turns the uuid to base62. – jonasbb Sep 07 '21 at 07:50
  • Thanks @jonasbb, but this isn’t specific to JSON right? What happens when we serialize to and from the db layer where we want the uuid and not base62? – maxcountryman Sep 07 '21 at 13:13
  • There is nothing specific for individual Serializers. The best is the human_readable flag, but if the DB layer is also human_readable that wouldn't help. In that case you will need to rely on some other information. You could use a thread_local variable to switch how to serialize the value. You could also think about wrapper types like serializing `Json` for a fitting definition of `Json`. – jonasbb Sep 07 '21 at 21:22

0 Answers0