Search code examples
rustserde-json

How can I deserialize a Vec<String> into a Vec<MyStruct> in Rust?


I have the following struct:

pub struct Data {
   num: i32,
   text: String,
}

I have a Vec<String> (let's call it myVecOfStrings) in which each element is a String that looks like:

"{ num: 1, text: \"a\"}"

How can I create a binding (variable) myVecOfStrings:Vec<String> of type Vec<Data>:

myVecOfData:Vec<Data> = ?

perhaps using serde_json, or any other library?

Note that this question is not exactly like Parsing a JSON String with serde_json, as that question does not address the issue of the String being inside a Vec.


Solution

  • Yes, you can do this with serde_json just by mapping over serde_json::from_str. Here is a generic function that can accept Vec<String> and returns a Result containing a Vec of any deserializable type:

    use serde::de::DeserializeOwned;
    
    pub fn parse_json_strings<T: DeserializeOwned, S: AsRef<str>>(
        items: impl IntoIterator<Item = S>,
    ) -> Result<Vec<T>, serde_json::Error> {
        items
            .into_iter()
            .map(|i| serde_json::from_str(i.as_ref()))
            .collect()
    }