简体   繁体   English

如何在不包含枚举变量名称的情况下序列化枚举?

[英]How do I serialize an enum without including the name of the enum variant?

I am trying to serialize an enum to a JSON string. 我正在尝试将枚举序列化为JSON字符串。 I implemented Serialize trait for my enum as it is described in the docs, but I always get {"offset":{"Int":0}} instead of the desired {"offset":0} . 我按照文档中的描述为我的枚举实现了Serialize特征,但是我总是得到{"offset":{"Int":0}}而不是所需的{"offset":0}

extern crate serde;
extern crate serde_json;

use std::collections::HashMap;

use serde::ser::{Serialize, Serializer};

#[derive(Debug)]
enum TValue<'a> {
    String(&'a str),
    Int(&'a i32),
}

impl<'a> Serialize for TValue<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            TValue::String(ref s) => serializer.serialize_newtype_variant("TValue", 0, "String", s),
            TValue::Int(i) => serializer.serialize_newtype_variant("TValue", 1, "Int", &i),
        }
    }
}

fn main() {
    let offset: i32 = 0;
    let mut request_body = HashMap::new();
    request_body.insert("offset", TValue::Int(&offset));
    let serialized = serde_json::to_string(&request_body).unwrap();
    println!("{}", serialized); // {"offset":{"Int":0}}
}

You can use the untagged attribute which will produce the desired output. 您可以使用untagged属性,它将产生所需的输出。 You won't need to implement Serialize yourself with this: 您不需要使用以下方法实现Serialize自己:

#[derive(Debug, Serialize)]
#[serde(untagged)]
enum TValue<'a> {
    String(&'a str),
    Int(&'a i32),
}

If you wanted to implement Serialize yourself, I believe you want to skip your variant so you should not use serialize_newtype_variant() as it exposes your variant. 如果您想自己实现Serialize ,我相信您想跳过您的变体,因此您不应使用serialize_newtype_variant()因为它会暴露您的变体。 You should use serialize_str() and serialize_i32() directly: 您应该直接使用serialize_str()serialize_i32()

impl<'a> Serialize for TValue<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            TValue::String(s) => serializer.serialize_str(s),
            TValue::Int(i) => serializer.serialize_i32(*i),
        }
    }
}

It produces the desired output: 它产生所需的输出:

{"offset":0}

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

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