如何将字符串字段反序列化为 bool

Ove*_*ivr 4 rust serde

我目前有一个 JSON 字符串,正在使用serde_json.

{
  "foo": "<val>" // val can contain "SI" or "NO"
}
Run Code Online (Sandbox Code Playgroud)

我想使用将其反序列化为 boolserde和将“SI”变为 true 的自定义查找,反之亦然。

#[derive(Deserialize)]
pub struct Entry {
   pub foo: bool, // How to express string to bool deserialization ?
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能简单地做到这一点?

Mar*_*her 12

deserialize_with你可以像这样使用:

#[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"])),
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅:https://play.rust-lang.org/? version=stable&mode=debug&edition=2021&gist=0ac9e89f97afc893197d37bc55dba188

  • nitpick:在错误情况下可能会调用“de::Error::unknown_variant()” (2认同)