简体   繁体   English

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

[英]How to remove enum variant tag from custom enum?

I define an enum ZcMapValue use as V for HashMap<K,V> , but when I serialize ZcMapValue to JSON, I got some problem, my code like the code bellow:我为HashMap<K,V>定义了一个enum ZcMapValue用作V ,但是当我将 ZcMapValue 序列化为ZcMapValue时,我遇到了一些问题,我的代码如下所示:

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);
}

When I run the code I want:当我运行我想要的代码时:

{"A_B": "a", "B_C": 128}

But the result is:但结果是:

{
  "B_C": {
    "longValue": 128
  },
  "A_B": {
    "stringValue": "a"
  }
}

How can I fixed it?我该如何解决?

To be able to get that format you can use #[serde(untagged)] .为了能够获得该格式,您可以使用#[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>),
}

Now your println!现在你的println! should correctly output:应该正确 output:

{
  "A_B": "a",
  "B_C": 128 
}

If you don't want it pretty printed, then you simply have to use serde_json::to_string() instead of serde_json::to_string_pretty() .如果您不希望它打印得很漂亮,那么您只需使用serde_json::to_string()而不是serde_json::to_string_pretty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM