More examples on OneOrMany and newtypes #649
-
I am stugglinh with OneOrMany on one of my types. I tried few of the things that I found in #308. But unfortunately, I can't get it to work and I also don't understand most of it :/ Here is a sample of my code: #[derive(Clone, Debug, Deserialize)]
struct ActionSet(HashMap<String, ActionList>);
#[serde_as]
#[derive(Clone, Debug, Deserialize)]
struct ActionList(
#[serde_as(deserialize_as = "OneOrMany<Action, PreferMany>")]
Vec<Action>
);
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Action {
Add(Value),
Remove(Value),
} In the HashMap contained in ActionSet I would like to always have Vectors of Actions. But my file might contain either an Action or a list of Actions. At the moment I keep getting:
When removing the type like in
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I tried adding an intermediary type like in: #[derive(Clone, Debug, Deserialize)]
struct ActionSet(HashMap<String, ActionList>);
#[derive(Clone, Debug, Deserialize)]
#[serde(from = "ActionListI")]
struct ActionList(Vec<Action>);
impl From<ActionListI> for ActionList {
fn from(item: ActionListI) -> Self {
return ActionList(item.vec);
}
}
#[serde_as]
#[derive(Clone, Debug, Deserialize)]
struct ActionListI {
// With our without #[serde(flatten)] here doesn't change anything
#[serde_as(deserialize_as = "OneOrMany<Action, PreferMany>")]
vec: Vec<Action>
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Action {
Add(Value),
Remove(Value),
} But it doesn't seem to help |
Beta Was this translation helpful? Give feedback.
-
Please check if #202 covers your issue too. Basically, if you want to use the default #[serde_as]
#[derive(Clone, Debug, Deserialize)]
struct ActionList(
#[serde_as(deserialize_as = "OneOrMany<_, PreferMany>")]
Vec<Action>
); |
Beta Was this translation helpful? Give feedback.
-
Hi @jonasbb, |
Beta Was this translation helpful? Give feedback.
Please check if #202 covers your issue too. Basically, if you want to use the default
Serialize
/Deserialize
behavior of a type, you have to write_
within theserde_as
attribute. In your case that would be