【发布时间】:2021-05-26 09:56:43
【问题描述】:
我有几个非详尽的枚举,我需要很好地处理它们。 当检测到未知变体时,我需要简单地忽略值并继续处理其他变体。
我目前正在反序列化来自的数据向量,并设法为我的应用程序正确获取 MyStruct 的向量。
我的应用程序需要与新版本的枚举向前兼容,并且简单地忽略未知的变体。
例如,目前:
use serde::{Deserialize};
#[derive(Deserialize, Debug)]
#[non_exhaustive]
pub enum CaseStyle {
Lowercase,
Uppercase,
}
#[derive(Deserialize, Debug)]
#[non_exhaustive]
pub enum Encoding {
Plain,
Base64,
}
#[derive(Deserialize, Debug)]
pub struct MyStruct {
case_style: CaseStyle,
encoding: Encoding,
}
fn main() {
let j = r#"[
{"case_style": "Lowercase","encoding":"Plain"},
{"case_style": "Snakecase","encoding":"Plain"},
{"case_style": "Lowercase","encoding":"Aes"},
{"case_style": "Uppercase","encoding":"Base64"}
]"#;
// Convert the JSON string to vec.
let deserialized: Vec<MyStruct> = serde_json::from_str(&j).unwrap();
// Prints deserialized = [MyStruct { case_style: Lowercase, encoding: Plain }, MyStruct { case_style: Uppercase, encoding: Base64 }]
println!("deserialized = {:?}", deserialized);
}
此示例失败,因为 json 数据中有 2 个未知变体。我怎么能从反序列化中忽略这些未知变体?
【问题讨论】:
-
encoding未知时应该解码成什么?你不想要一个Option<Encoding>吗? -
Does this回答你的问题?
-
@DenysSéguret 这不是实际代码,而是我需要的更多示例。我不能简单地更改
encoding的类型,因为这意味着检查字段是 Some 还是 None。
标签: rust deserialization serde