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

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}

Leave a Comment