sonic-rs icon indicating copy to clipboard operation
sonic-rs copied to clipboard

Error when deserializing `Value` to `T`

Open rieval opened this issue 1 year ago • 2 comments

Hello! I'm trying to write a helper function that deserializes Value to T and returns a default value if deserialization fails. I noticed that if I replace sonic_rs with serde_json, it's works.

Here is a example code:

pub fn deserialize_skip_error<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: serde::Deserialize<'de> + Default,
    D: serde::Deserializer<'de>,
{
    let value = sonic_rs::Value::deserialize(deserializer)?;
    let inner = T::deserialize(value).unwrap_or_default();
    Ok(inner)
}

And error logs here:

the trait bound `sonic_rs::Value: extract_id::_::_serde::Deserializer<'_>` is not satisfied
the trait `extract_id::_::_serde::Deserializer<'_>` is not implemented for `sonic_rs::Value`
but it is implemented for `&sonic_rs::Value` for that trait implementation, expected `&sonic_rs::Value`, found `sonic_rs::Value`

Windows 11 rustc 1.86.0-nightly (bef3c3b01 2025-02-04)

crates version: sonic_rs: main branch serde: 1.0.216

rieval avatar Feb 08 '25 08:02 rieval

thanks. I got it. will fixed later

liuq19 avatar Feb 08 '25 11:02 liuq19

recommend changing serde::Deserialize<'de> to be DeserializeOwned to workaround the problem as follows

pub fn deserialize_skip_error<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: DeserializeOwned + Default,
    D: serde::Deserializer<'de>,
{
    let value = sonic_rs::Value::deserialize(deserializer)?;
    let inner = T::deserialize(&value).unwrap_or_default();
    Ok(inner)
}

liuq19 avatar Oct 13 '25 06:10 liuq19