我定义了enum ZcMapValue
用作V
的HashMap<K,V>
,但是当我将ZcMapValue
序列化为JSON时,出现了一些问题,我的代码如下所示:
use serde::Serialize;
use std::collections::HashMap;
#[derive(Clone, Debug, Serialize)]
pub enum ZcMapValue {
LongValue(i128),
FloatValue(f64),
BoolValue(bool),
StringValue(String),
VecValue(Vec<ZcMapValue>),
VecMapValue(Vec<HashMap<String, ZcMapValue>>),
MapValue(HashMap<String, ZcMapValue>),
}
fn main() {
let mut map = HashMap::new();
map.insert("A_B".to_string(), ZcMapValue::StringValue("a".to_string()));
map.insert("B_C".to_string(), ZcMapValue::LongValue(128));
let ser_js = serde_json::to_string_pretty(&map).unwrap();
println!("{}", ser_js);
}
当我运行代码时,我想要:{"A_B": "a", "B_C": 128}
但是结果是:{
"B_C": {
"longValue": 128
},
"A_B": {
"stringValue": "a"
}
}
我该如何解决?
最佳答案
要获得该格式,可以使用 #[serde(untagged)]
。
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum ZcMapValue {
LongValue(i128),
FloatValue(f64),
BoolValue(bool),
StringValue(String),
VecValue(Vec<ZcMapValue>),
VecMapValue(Vec<HashMap<String, ZcMapValue>>),
MapValue(HashMap<String, ZcMapValue>),
}
现在,您的println!
应该正确输出:{
"A_B": "a",
"B_C": 128
}
如果您不希望它漂亮地打印出来,那么您只需要使用 serde_json::to_string()
而不是 serde_json::to_string_pretty()
即可。
关于json - 如何从自定义枚举中删除枚举变体标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65529983/