Module serde_with::rust::seq_display_fromstr
source · [−]Expand description
De/Serialize sequences using FromIterator and IntoIterator implementation for it and Display and FromStr implementation for each element
This allows to serialize and deserialize collections with elements which can be represented as strings.
Converting to serde_as
The same functionality can be more clearly expressed via DisplayFromStr and using the serde_as macro.
Instead of
ⓘ
#[serde(with = "serde_with::rust::seq_display_fromstr")]
addresses: BTreeSet<Ipv4Addr>,you can write:
ⓘ
#[serde_as(as = "BTreeSet<DisplayFromStr>")]
addresses: BTreeSet<Ipv4Addr>,This works for any container type, so also for Vec:
ⓘ
#[serde_as(as = "Vec<DisplayFromStr>")]
bs: Vec<bool>,Examples
use std::collections::BTreeSet;
use std::net::Ipv4Addr;
#[derive(Deserialize, Serialize)]
struct A {
#[serde(with = "serde_with::rust::seq_display_fromstr")]
addresses: BTreeSet<Ipv4Addr>,
#[serde(with = "serde_with::rust::seq_display_fromstr")]
bs: Vec<bool>,
}
let v: A = serde_json::from_str(r#"{
"addresses": ["192.168.2.1", "192.168.2.2", "192.168.1.1", "192.168.2.2"],
"bs": ["true", "false"]
}"#).unwrap();
assert_eq!(v.addresses.len(), 3);
assert!(v.addresses.contains(&Ipv4Addr::new(192, 168, 2, 1)));
assert!(v.addresses.contains(&Ipv4Addr::new(192, 168, 2, 2)));
assert!(!v.addresses.contains(&Ipv4Addr::new(192, 168, 1, 2)));
assert_eq!(v.bs.len(), 2);
assert!(v.bs[0]);
assert!(!v.bs[1]);
let x = A {
addresses: vec![
Ipv4Addr::new(127, 53, 0, 1),
Ipv4Addr::new(127, 53, 1, 1),
Ipv4Addr::new(127, 53, 0, 2)
].into_iter().collect(),
bs: vec![false, true],
};
assert_eq!(
r#"{"addresses":["127.53.0.1","127.53.0.2","127.53.1.1"],"bs":["false","true"]}"#,
serde_json::to_string(&x).unwrap()
);Functions
Deserialize collection T using FromIterator and FromStr for each element
Serialize collection T using IntoIterator and Display for each element