Help with deserialization

Hi everybody

I use serde_json to parse a generic struct to a json. So far so good. But the other way around, the &str containing the json and the deserialized struct must have the same lifetime according to the library.
I understand why the follwoing code is not working but I can't find a way to achieve it? (Passing out the &str trough the whole program is not a very nice option)

pub(crate) async fn load_json<'a, T1: AsRef<Path>, T2: Deserialize<'a> + Clone>(src_file: T1, mut value: T2) -> Result<(), Error> {
    let mut data = String::new();
    let mut f = File::open(src_file.as_ref())?;
    f.read_to_string(&mut data)?;
    value = serde_json::from_str(&data)?;
    Ok(())
}

Restrict T to implement the DeserializeOwned trait instead. That tells the compiler that you only want to allow types that aren't going to hold a reference to the original string data. (e.g. only String and not &str is allowed)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.