How can I skip deserializing and use default if field is null without wrapping thing in an option type in serde?

How can I skip deserializing and use default is field is null without wrapping thing in an option type in serde?

I'm not sure if this is the simplest way to do it, but it works:

use serde::{Deserialize, Deserializer};

fn null_to_default<'de, D, T>(d: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Default + Deserialize<'de>,
{
    let opt = Option::deserialize(d)?;
    let val = opt.unwrap_or_else(T::default);
    Ok(val)
}

#[derive(Deserialize)]
struct Foo {
    #[serde(deserialize_with = "null_to_default")]
    bar: u32,
}
1 Like

Is the option here std::option::Option?

Yes.

thanks this will save me a lot of pain

https://serde.rs/field-attrs.html#default

That doesn't work when the value is null, only when it is missing.

1 Like