Reputation: 11
So i am writing a program in Rust (which I am very new to), that reads a json configuration file and does some stuff depending on the input. I have managed to parse the json successfully using serde_json. The next thing i want to allow the user to do is to be able to specify some advanced options but i don't know how to parse the input. The default json would look something like this:
{
value: true
}
Parsing this is straight forward to a struct like this:
#[derive(Deserialize)]
pub struct Config {
value: bool
}
How would i go about adding the option for the user to be able to input either a bool
or an object
as such:
{
value: {
avanced_value: true
}
}
I have tried using an enum
like this but it seems bool
can not be used within an enum.
#[derive(Deserialize)]
pub struct Config {
value: ValueEnum
}
#[derive(Deserialize)]
pub enum ValueEnum {
bool,
Config(ValueConfig),
}
#[derive(Deserialize)]
pub struct ValueConfig {
advanced_value: bool
}
Am I missing something obvious or should I restructure the input json? Tnx in advance.
Upvotes: 0
Views: 750
Reputation: 316
You didn't wrap the bool in an enum variant (like you did with ValueConfig). Also by default, serde tags enums, which is probably not what you want. You want to use an untagged enum:
#[derive(Deserialize)]
pub struct Config {
value: ValueEnum
}
#[derive(Deserialize)]
#[serde(untagged)]
pub enum ValueEnum {
Bool(bool),
Config(ValueConfig),
}
#[derive(Deserialize)]
pub struct ValueConfig {
advanced_value: bool
}
Upvotes: 1