Skip to main content

optional

Function optional 

Source
pub fn optional<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where D: Deserializer<'de>, T: Deserialize<'de> + FromStr, T::Err: Display,
Expand description

Deserializes an optional field where null, a missing value or an empty string is None.

Use on Option<T> fields with #[serde(default, deserialize_with = "ocre::optional")] (default makes a missing key None). A typed value (42) is taken as is; a blank string (only whitespace) is None; any other string ("42", as HTML forms send) is parsed with T::from_str.

§Errors

Fails with the deserializer’s error, carrying T::Err’s message, when a non-empty string does not parse. Behind Json that is a JSON 400.

§Examples

use serde::Deserialize;

#[derive(Deserialize)]
struct Book {
    #[serde(default, deserialize_with = "ocre::optional")]
    pages: Option<i64>,
}

let parse = |json| serde_json::from_str::<Book>(json).map(|book| book.pages);
assert_eq!(parse(r#"{"pages": 320}"#).unwrap(), Some(320));
assert_eq!(parse(r#"{"pages": "320"}"#).unwrap(), Some(320));
assert_eq!(parse(r#"{"pages": ""}"#).unwrap(), None);
assert_eq!(parse(r#"{"pages": null}"#).unwrap(), None);
assert_eq!(parse("{}").unwrap(), None);
assert!(parse(r#"{"pages": "many"}"#).is_err());