Expand description

Deserialize value and return Default on error

The main use case is ignoring error while deserializing. Instead of erroring, it simply deserializes the Default variant of the type. It is not possible to find the error location, i.e., which field had a deserialization error, with this method.

Converting to serde_as

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

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

Examples

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

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

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

// String is of invalid type
let a: A = serde_json::from_str(r#"{"value": "123"}"#).unwrap();
assert_eq!(0, a.value);

// Map is of invalid type
let a: A = serde_json::from_str(r#"{"value": {}}"#).unwrap();
assert_eq!(0, a.value);

// Missing entries still cause errors
assert!(serde_json::from_str::<A>(r#"{  }"#).is_err());

Deserializing missing values can be supported by adding the default field attribute:

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

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

Functions

Deserialize T and return the Default value on error

Serialize value with the default serializer