Module serde_with::rust::default_on_error [−][src]
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.
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); // 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 |