Skip to main content

deserialize_some

Function deserialize_some 

Source
pub fn deserialize_some<'de, D, T>(
    deserializer: D,
) -> Result<Option<T>, D::Error>
where D: Deserializer<'de>, T: Deserialize<'de>,
Expand description

Deserializer function that always produces Some(T) if a value is present.

It is useful when one wants to distinguish between a field that’s absent and a field that’s present with a null value. For example, the annotation below may be used for a field that may be absent, but may not be null.

    #[serde(
        default,
        deserialize_with = "::json_serde::deserialize_some",
        skip_serializing_if = "Option::is_none",
    )]
    field: Option<String>,

It can also be used with a “double-Option” to determine whether a field was absent, null, or had a value:

    #[serde(
        default,
        deserialize_with = "::json_serde::deserialize_some",
        skip_serializing_if = "Option::is_none",
    )]
    field: Option<Option<String>>,

In the first case, a null value results in an error because a String cannot be deserialized from null. In the second case, a null value results in field having a value of Some(None) since Option<String> can be deserialized from null.