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