Using serde_with to deserialize from string or struct on a vector
#333
-
|
Thanks for the crate @jonasbb! Building off this example, which is an extension from serde's docs. We'll assume we have the same struct #[derive(Debug, Deserialize)]
struct Build {
context: String,
dockerfile: Option<String>,
#[serde(default)]
args: Map<String, String>,
}Let's now assume we wanted to deserialize potentially many of them, e.g our target struct is: #[derive(Deserialize, Debug)]
pub struct ManyBuilds {
some_fields_with_overall_info: i32, // etc
builds: Vec<Build>
}@jonasbb's suggestion is to annotate #[derive(Deserialize, Debug)]
pub struct ManyBuilds {
some_fields_with_overall_info: i32, // etc
#[serde_as(as = "Vec<PickFirst<(_, DisplayFromStr)>>")]
builds: Vec<Build>
}This looks great, although I am currently getting the following error: error: expected an inert attribute, found an attribute macro
--> src/main.rs:90:5
|
90 | #[serde_as(as = "Vec<PickFirst<(_, DisplayFromStr)>>")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous errorI'm guessing there's some very simple solution, but I don't yet see it. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
That is my mistake, I was too brief in the other message. To use #[serde_with::serde_as]
#[derive(Deserialize, Debug)]
pub struct ManyBuilds {
some_fields_with_overall_info: i32, // etc
#[serde_as(as = "Vec<PickFirst<(_, DisplayFromStr)>>")]
builds: Vec<Build>
}Side-Note: The associated |
Beta Was this translation helpful? Give feedback.
That is my mistake, I was too brief in the other message. To use
serde_asyou need to place the proc-macro attribute#[serde_with::serde_as]before thederive. This section of the user guide explains how to setup everything and what you can do with it.Side-Note: The associated
Errtype on theFromStrimplementations needs to implementDisplayfor this to work.