【发布时间】:2021-04-08 07:35:21
【问题描述】:
我为HashMap<K,V> 定义了一个enum ZcMapValue 用作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"
}
}
我该如何解决?
【问题讨论】:
-
我希望我简化了您的代码以更好地突出问题 :)
标签: json rust enums hashmap serde