Consider this code:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct {
my_enum: MyEnum,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
enum MyEnum {
TypeA {
foo: usize,
},
TypeB {
bar: usize,
}
}
fn main() {
let s = MyStruct {
my_enum: MyEnum::TypeA {
foo: 42,
},
};
println!("{}", serde_json::to_string_pretty(&s).unwrap());
}
Right now it prints this:
{
"my_enum": {
"type": "type_a",
"foo": 42
}
}
I want it to print this:
{
"type": "type_a",
"my_enum": {
"foo": 42
}
}
I was able to achieve this with this code:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct {
#[serde(flatten)]
my_enum: MyEnum,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "my_enum")]
#[serde(rename_all = "snake_case")]
enum MyEnum {
TypeA {
foo: usize,
},
TypeB {
bar: usize,
}
}
fn main() {
let s = MyStruct {
my_enum: MyEnum::TypeA {
foo: 42,
},
};
println!("{}", serde_json::to_string_pretty(&s).unwrap());
}
But it basically radically changes the serialized form of MyEnum
, and I want to avoid that. Is there another way to do it, so that MyEnum
serialization behaviour remains default?