Module serde_with::rust::display_fromstr
source · [−]Expand description
De/Serialize using Display and FromStr implementation
This allows deserializing a string as a number. It can be very useful for serialization formats like JSON, which do not support integer numbers and have to resort to strings to represent them.
If you control the type you want to de/serialize, you can instead use the two derive macros, SerializeDisplay and DeserializeFromStr.
They properly implement the traits Serialize and Deserialize such that user of the type no longer have to use the with-attribute.
Converting to serde_as
The same functionality can be more clearly expressed via DisplayFromStr and using the serde_as macro.
#[serde_as]
#[derive(Deserialize)]
struct A {
#[serde_as(as = "DisplayFromStr")]
value: mime::Mime,
}Examples
#[derive(Deserialize, Serialize)]
struct A {
#[serde(with = "serde_with::rust::display_fromstr")]
mime: mime::Mime,
#[serde(with = "serde_with::rust::display_fromstr")]
number: u32,
}
let v: A = serde_json::from_str(r#"{
"mime": "text/plain",
"number": "159"
}"#).unwrap();
assert_eq!(mime::TEXT_PLAIN, v.mime);
assert_eq!(159, v.number);
let x = A {
mime: mime::STAR_STAR,
number: 777,
};
assert_eq!(
r#"{"mime":"*/*","number":"777"}"#,
serde_json::to_string(&x).unwrap()
);Functions
Deserialize T using FromStr