Skip to content

Serialize a Uuid field in a struct to NULL if it is default() #856

Answered by jonasbb
ronnybremer asked this question in Q&A
Discussion options

You must be logged in to vote

There is nothing in the crate like this. There are no guarantees around Default::default() that can be made, so there are no pre-made conversions implemented.

I think something like this should work. I haven't compiled it. It basically converts the Uuid to Option<Uuid> based on the is_nil.

serde_with::serde_conv!(
    UuidNilAsNone,
    Uuid,
    |uuid: &Uuid| if uuid.is_nil() {None} else Some(uuid),
    |value: Option<Uuid>| -> Result<_, std::convert::Infallible> {
        Ok(value.unwrap_or_default())
    }
);

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@ronnybremer
Comment options

@ronnybremer
Comment options

@jonasbb
Comment options

Answer selected by ronnybremer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants