#[serde_as(as = Option<...>)] does not allow field to be missing #183
-
I'm trying to deserialize one optional field from comma-separated string: #[serde_as]
#[derive(Deserialize, Debug)]
struct Query {
search: Option<String>,
#[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
priority: Option<Vec<u32>>,
}
#[test]
fn test_queries() {
let query1 = "priority=2,3";
let q1: Result<Query, _> = serde_urlencoded::from_str(query1);
println!("ok: {:?}", q1);
let query2 = "search=ttt";
let q2: Result<Query, _> = serde_urlencoded::from_str(query2);
println!("fail: {:?}", q2);
} But it doesn't allow that field to be missing:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
This unfortunately a side effect of using If you provide serde's #[serde_as]
#[derive(Deserialize, Debug)]
struct Query {
search: Option<String>,
#[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
#[serde(default)]
priority: Option<Vec<u32>>,
} If you do not care about the distinction between #[serde_as(as = "StringWithSeparator::<CommaSeparator, u32>")]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
priority: Vec<u32>, The I hope this helps you :) |
Beta Was this translation helpful? Give feedback.
-
Thanks! First solution works for me. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the feedback, I will consider that as an option. |
Beta Was this translation helpful? Give feedback.
This unfortunately a side effect of using
deserialize_with
. I see how I can better document the pitfall.If you provide serde's
default
attribute, then it behaves as expected. It will deserialize aNone
in this case:If you do not care about the distinction between
priority
was provided but the list is empty andpriority
is missing, you can also remove theOption
frompriority
: