既存の列挙型逆シリアル化を使用できます。フォーマットを次の列挙型に逆シリアル化するための段階的な例を示します。
#[derive(Debug, PartialEq, Eq, Deserialize)]
enum MyType {
A {gar: ()},
B {test: i32},
C {blub: String},
}
json 文字列の例から始めます。
let json = r#"{"type": "B", "test": 42}"#;
Value
列挙型に変換します
let mut json: serde_json::Value = serde_json::from_str(json).unwrap();
type
フィールドを引き裂く
let type_ = {
let obj = json.as_object_mut().expect("object");
let type_ = obj.remove("type").expect("`type` field");
if let serde_json::Value::String(s) = type_ {
s
} else {
panic!("type field not a string");
}
};
「適切な」列挙型 json を作成します。フィールドの名前が列挙バリアントであり、フィールドの値がバリアント値である単一のフィールドを持つ構造体
let mut enum_obj = std::collections::BTreeMap::new();
enum_obj.insert(type_, json);
let json = serde_json::Value::Object(enum_obj);
生成された json デシリアライザーを使用して、json を列挙型の値に変換します
let obj: MyType = serde_json::from_value(json).unwrap();