pub fn deserialize_default_from_empty_object<'de, D, T>(
deserializer: D,
) -> Result<T, D::Error>
Expand description
Deserializes default value from nullable value or empty object. If the original value is null
or {}
,
Default::default()
is used.
ยงExample:
use serde_aux::prelude::*;
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_default_from_empty_object")]
empty_as_default: Option<MyInnerStruct>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyInnerStruct {
mandatory: u64,
}
let s = r#" { "empty_as_default": { "mandatory": 42 } } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.empty_as_default.unwrap().mandatory, 42);
let s = r#" { "empty_as_default": null } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.empty_as_default.is_none());
let s = r#" { "empty_as_default": {} } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert!(a.empty_as_default.is_none());
let s = r#" { "empty_as_default": { "unknown": 42 } } "#;
assert!(serde_json::from_str::<MyStruct>(s).is_err());