I currently have a JSON string I am deserializing with serde_json
.
{
"foo": "<val>" // val can contain "SI" or "NO"
}
I would like to deserialize this to a bool using serde
and a custom lookup that turns "SI" -> true and vice-versa.
#[derive(Deserialize)]
pub struct Entry {
pub foo: bool, // How to express string to bool deserialization ?
}
How can I do that simply ?
You could use deserialize_with
like so:
#[derive(Deserialize)]
pub struct Entry {
#[serde(deserialize_with = "deserialize_bool")]
pub foo: bool,
}
fn deserialize_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: de::Deserializer<'de>,
{
let s: &str = de::Deserialize::deserialize(deserializer)?;
match s {
"SI" => Ok(true),
"NO" => Ok(false),
_ => Err(de::Error::unknown_variant(s, &["SI", "NO"])),
}
}