Skip to content

How to use serde_as with vec of my type? #395

Answered by jonasbb
Magicloud asked this question in Q&A
Discussion options

You must be logged in to vote

Hi, as written, the code tries to use the Display an FromStr implementations of Vec to perform the serialization. These do not exist, which is why you see the error. What you want is to apply the DisplayFromStr conversion on each element of the Vec. You write this as:

#[serde_with::serde_as] // You also need to add this line in front of each struct/enum where you use serde_as
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct MyStruct {
    #[serde_as(as = "Vec<DisplayFromStr>")]
    field: Vec<MyType>,
}

Other container types (e.g., Option, BTreeMap, HashSet) work the same way, by using the collection type for the field and inside serde_as.

If you work with a type you defi…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Magicloud
Comment options

Answer selected by Magicloud
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #394 on December 31, 2021 16:26.