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

前端 未结 1 2007
天命终不由人
天命终不由人 2020-11-30 15:22

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\":

相关标签:
1条回答
  • 2020-11-30 16:06

    You can use the untagged attribute which will produce the desired output. You won't need to implement Serialize yourself with this:

    #[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. You should use serialize_str() and serialize_i32() directly:

    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}
    
    0 讨论(0)
提交回复
热议问题