serde_html_form
(De-)serialization support for the application/x-www-form-urlencoded
format.
This crate is a Rust library for serialising to and deserialising from
the application/x-www-form-urlencoded
format. It is built
upon Serde, a high performance generic serialization framework and rust-url,
a URL parser for Rust.
It is a fork of serde_urlencoded
, with additional support for maps or
structs with fields of sequence type (e.g. Vec<String>
). It also supports
Option
in values, treating foo=
as foo: None
.
Examples
Sequences like value=x&value=y
:
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
struct Form {
#[serde(default)]
value: Vec<String>,
}
assert_eq!(
serde_html_form::from_str("value=&value=abc"),
Ok(Form { value: vec!["".to_owned(), "abc".to_owned()] })
);
assert_eq!(
serde_html_form::from_str(""),
Ok(Form { value: vec![] })
);
Sequences like value[]=x&value[]=y
:
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
struct Form {
#[serde(default, rename = "value[]")]
value: Vec<String>,
}
assert_eq!(
serde_html_form::from_str("value[]=x&value[]=y"),
Ok(Form { value: vec!["x".to_owned(), "y".to_owned()] })
);
assert_eq!(
serde_html_form::from_str("value[]=hello"),
Ok(Form { value: vec!["hello".to_owned()] })
);
Optional values:
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
struct Form {
single: Option<u32>,
at_least_one: Vec<Option<u32>>,
}
assert_eq!(
serde_html_form::from_str("at_least_one=5"),
Ok(Form {
single: None,
at_least_one: vec![Some(5)],
})
);
assert_eq!(
serde_html_form::from_str("at_least_one=&single=1&at_least_one=5"),
Ok(Form {
single: Some(1),
at_least_one: vec![
None,
Some(5),
]
})
);
assert!(
serde_html_form::from_str::<Form>("").is_err(),
"at_least_one is not part of the input"
);
License
This crate is licensed under the MIT license (LICENSE or
https://opensource.org/license/mit/).