gpt4 book ai didi

rust - 我可以用 serde 序列化枚举的定义吗?

转载 作者:行者123 更新时间:2023-12-05 03:28:01 25 4
gpt4 key购买 nike

给定这个枚举定义:

#[repr(u8)]
#[derive(Debug, Serialize)]
pub enum AnimalType {
#[serde(rename = "cat")]
Cat = 1,
#[serde(rename = "dog")]
Dog = 2,
#[serde(rename = "snake")]
Snake = 3,
#[serde(rename = "capybara")]
Capybara = 4,
}

我希望能够返回定义上述枚举的 JSON,类似于:

{
"AnimalType": [
{ "cat": 1 },
{ "dog": 2 },
{ "snake": 3 },
{ "capybara": 4 }
]
}

是否可以在 Rust 中以编程方式执行此操作,可能使用 serde

这个问题不同于How do I configure Serde to use an enum variant's discriminant rather than name?因为我想序列化枚举的定义,而不是

最佳答案

我最终使用了 strum 及其 EnumVariantNames 宏:https://docs.rs/strum_macros/latest/strum_macros/derive.EnumVariantNames.html

#[repr(u8)]
#[derive(Serialize, EnumVariantNames)]
pub enum AnimalType {
#[serde(rename = "cat")]
#[strum(serialize = "cat")]
Cat = 1,
#[serde(rename = "dog")]
#[strum(serialize = "dog")]
Dog = 2,
#[serde(rename = "SNAKE")]
#[strum(serialize = "SNAKE")]
Snake = 3,
#[serde(rename = "capybara")]
#[strum(serialize = "capybara")]
Capybara = 4,
}

async fn get_animal_types() -> Result<impl warp::Reply, warp::Rejection> {
Ok(warp::reply::json(&AnimalType::VARIANTS))
}

返回 ["cat","dog","SNAKE","capybara"]

关于rust - 我可以用 serde 序列化枚举的定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71309868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com