I am trying to serialize an enum to a JSON string. 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}
.
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}}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…