pub fn deserialize_skip_error<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where T: Deserialize<'de> + Default, D: Deserializer<'de>,
Expand description

Attempts to deserialize item, in case of error falls back to the type’s default value.

Useful for optional fields which are sent with a different type from another platform, eg object instead of array. Should always be used together with #[serde(default)], so that a mssing value doesn’t cause an error.

#[derive(serde::Deserialize)]
struct Note {
    content: String,
    #[serde(deserialize_with = "deserialize_skip_error", default)]
    source: Option<String>
}

let note = serde_json::from_str::<Note>(
r#"{
    "content": "How are you?",
    "source": {
        "content": "How are you?",
        "mediaType": "text/markdown"
    }
}"#);
assert_eq!(note.unwrap().source, None);