如何在 json 中表示 serde 的枚举变体?

问题描述 投票:0回答:1

我正在尝试从文本创建对象,所以我决定使用 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 提供任何值,并因此引发运行时错误.

oop rust type-conversion serde
1个回答
0
投票

枚举的默认编码是外部标记。一个例子:

{
    "kind": {
        "Particle": {
            "mass": 0.1
        }
    }
}

但是,您可以通过多种方式对其进行自定义,请参阅上面链接的页面。

© www.soinside.com 2019 - 2024. All rights reserved.