Fix deserialize_skip_error function

https://github.com/serde-rs/serde/issues/1726#issuecomment-577425541
This commit is contained in:
Felix Ableitner 2023-02-05 00:49:10 +09:00
parent 5b8ad33c60
commit d933b8aeb4

View file

@ -58,9 +58,26 @@ where
T: Deserialize<'de> + Default,
D: Deserializer<'de>,
{
let result = Deserialize::deserialize(deserializer);
Ok(match result {
Ok(o) => o,
Err(_) => Default::default(),
})
let value = serde_json::Value::deserialize(deserializer)?;
let inner = T::deserialize(value).unwrap_or_default();
Ok(inner)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deserialize_skip_error() {
#[derive(Debug, Deserialize)]
pub struct MyData {
#[serde(deserialize_with = "deserialize_skip_error")]
pub data: Option<String>,
}
// data has type object
let _: MyData = serde_json::from_str(r#"{ "data": {} }"#).unwrap();
// data has type array
let _: MyData = serde_json::from_str(r#"{"data": []}"#).unwrap();
}
}