如何从自定义枚举中删除枚举变体标签?

How to remove enum variant tag from custom enum?

我为 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"
  }
}

我该如何解决?

要获得该格式,您可以使用 #[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() instead of serde_json::to_string_pretty().