【问题标题】:How to remove enum variant tag from custom enum?如何从自定义枚举中删除枚举变体标签?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多