pub fn deserialize_bool_from_anything<'de, D>(
deserializer: D,
) -> Result<bool, D::Error>where
D: Deserializer<'de>,
Expand description
Deserializes boolean from anything (string, number, boolean). If input is a string,
it is expected, that it is possible to convert it to a number. The return boolean is
true
if the number was either 1
or 1.0
after parsing.
ยงExample
use serde_aux::prelude::*;
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_bool_from_anything")]
boolean: bool,
}
let s = r#"{ "boolean": 1.0 }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.boolean);
let s = r#"{ "boolean": 0.0 }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(!a.boolean);
let s = r#"{ "boolean": 2.3 }"#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());
let s = r#"{ "boolean": 1 }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.boolean);
let s = r#"{ "boolean": 0 }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(!a.boolean);
let s = r#"{ "boolean": 2 }"#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());
let s = r#"{ "boolean": "1.0" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.boolean);
let s = r#"{ "boolean": "0.0" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(!a.boolean);
let s = r#"{ "boolean": "2.3" }"#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());
let s = r#"{ "boolean": "1" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.boolean);
let s = r#"{ "boolean": "0" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(!a.boolean);
let s = r#"{ "boolean": "2" }"#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());
let s = r#"{ "boolean": "foo" }"#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());