【问题标题】:How to deserialize a string field to bool如何将字符串字段反序列化为布尔值
【发布时间】:2021-11-25 17:02:08
【问题描述】:

我目前有一个 JSON 字符串,我正在使用 serde_json 反序列化。

{
  "foo": "<val>" // val can contain "SI" or "NO"
}

我想使用serde 将其反序列化为布尔值,并使用自定义查找将“SI”-> 变为真,反之亦然。

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

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

【问题讨论】:

    标签: rust serde


    【解决方案1】:

    你可以像这样使用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"])),
        }
    }
    

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

    【讨论】:

    • nitpick: de::Error::unknown_variant() 可能在错误情况下被调用
    • @user2722968 好位置,已调整。
    猜你喜欢
    • 2017-10-20
    • 2014-08-06
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2020-08-08
    • 2020-05-20
    相关资源
    最近更新 更多