Expand description

Deserialize default value if encountering null.

One use case are JSON APIs in which the null value represents some default state. This adapter allows to turn the null directly into the Default value of the type.

Converting to serde_as

The same functionality can be more clearly expressed via DefaultOnNull and using the serde_as macro. It can be combined with other convertes as shown.

#[serde_as]
#[derive(Deserialize)]
struct A {
    #[serde_as(as = "DefaultOnNull")]
    value: u32,
    #[serde_as(as = "DefaultOnNull<DisplayFromStr>")]
    value2: u32,
}

Examples

#[derive(Deserialize)]
struct A {
    #[serde(deserialize_with = "serde_with::rust::default_on_null::deserialize")]
    value: u32,
}

let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
assert_eq!(123, a.value);

let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
assert_eq!(0, a.value);

// String is invalid type
assert!(serde_json::from_str::<A>(r#"{"value": "123"}"#).is_err());

Functions

Deserialize T and return the Default value if original value is null

Serialize value with the default serializer