[Solved] Serde deserialization on_error use default values?


#1

I am using serde for a project and I would like to deserialize an object like the following:

#[derive(Deserialize, Clone, Debug)]
pub struct ParentObject {
    unique_id: String,
    super_complicated_object:  MegaAwesomeObject
}

Since MegaAwesomeObject is very complicated, it will be occasionally prone to errors in case the payload is provided incorrectly. If that does occur, I do not want to error out on the ParentObject deserialization as well, since I do not want to lose the record of the unique_id. Is there a way for me to somehow use the default value for MegaAwesomeObject in case the deserialization fails?

Thank you for the help.


#2
use serde::{Deserialize, Deserializer};
use serde_json::Value;

#[derive(Deserialize, Clone, Debug)]
pub struct ParentObject {
    unique_id: String,
    #[serde(deserialize_with = "ok_or_default")]
    super_complicated_object: MegaAwesomeObject,
}

fn ok_or_default<T, D>(deserializer: D) -> Result<T, D::Error>
    where T: Deserialize + Default,
          D: Deserializer
{
    let v: Value = Deserialize::deserialize(deserializer)?;
    Ok(T::deserialize(v).unwrap_or_default())
}

#3

Thank you very much, the solution appears to be what I need.