How do I represent enum variants in json for serde?

40 views Asked by At

I'm trying to create objects from text, so I decided to use serde, but I'm struggling to write json for enum variants. This is a simplified version of the OOP I want to convert json to:

#[derive(Debug, Serialize, Deserialize)]
struct Spell {
    kind: Kind
}
#[derive(Debug, Serialize, Deserialize)]
enum Kind {
    Particle(Particle)
}
#[derive(Debug, Serialize, Deserialize)]
struct Particle {
    mass: f64
}

I'm using this simple function to turn the json into the a Spell object:

fn create_spell_from_json(spell_json: &str) -> Result<Spell, serde_json::Error> {
    let spell: Spell = serde_json::from_str(spell_json)?;
    Ok(spell)
}

So now how do I represent Particle in json? I'm not sure if it's possible, if not, I'm very open to suggestions as so far all I can write is this: {"kind": "Particle"} But this doesn't give any values to Particle and throws a runtime error because of it.

1

There are 1 answers

0
Chayim Friedman On BEST ANSWER

The default encoding for enums is externally tagged. An example:

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

However you can customize it in many ways, see the page linked above.