3

我正在尝试将枚举序列化为 JSON 字符串。我为我的枚举实现Serialize了 trait,正如文档中描述的那样,但我总是得到{"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}}
}
4

1 回答 1

10

您可以使用untagged将产生所需输出的属性。你不需要Serialize用这个来实现自己:

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

如果你想Serialize自己实现,我相信你想跳过你的变体,所以你不应该使用serialize_newtype_variant()它,因为它暴露了你的变体。您应该直接使用 serialize_str()and 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),
        }
    }
}

它产生所需的输出:

{"offset":0}
于 2018-08-27T08:07:50.370 回答