[][src]Module serde_with::rust::default_on_error

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. The _ is a placeholder which works for any type which implements Serialize/Deserialize, such as the tuple and u32 type.

#[serde_as]
#[derive(Deserialize)]
struct A {
    #[serde_as(as = "DefaultOnError")]
    value: 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

Deserialize T and return the Default value on error

serialize

Serialize value with the default serializer