我正在尝试从文本创建对象,所以我决定使用 serde,但我正在努力为枚举变体编写 json。这是我想要将 json 转换为的 OOP 的简化版本:
#[derive(Debug, Serialize, Deserialize)]
struct Spell {
kind: Kind
}
#[derive(Debug, Serialize, Deserialize)]
enum Kind {
Particle(Particle)
}
#[derive(Debug, Serialize, Deserialize)]
struct Particle {
mass: f64
}
我正在使用这个简单的函数将 json 转换为
Spell
对象:
fn create_spell_from_json(spell_json: &str) -> Result<Spell, serde_json::Error> {
let spell: Spell = serde_json::from_str(spell_json)?;
Ok(spell)
}
那么现在我该如何在 json 中表示 Particle 呢?我不确定是否可能,如果不可能,我非常愿意接受建议,因为到目前为止我能写的就是:
{"kind": "Particle"}
但这不会为 Particle 提供任何值,并因此引发运行时错误.