简体   繁体   中英

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:

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)] .

#[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! should correctly 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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