我目前有一个 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)
| 归档时间: |
|
| 查看次数: |
3640 次 |
| 最近记录: |