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

编程入门 行业动态 更新时间:2024-10-26 17:21:15
本文介绍了如何在不包含枚举变量名称的情况下序列化枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将枚举序列化为JSON字符串.正如文档中所述,我为我的枚举实现了Serialize特质,但是我总是得到{"offset":{"Int":0}}而不是所需的{"offset":0}.

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}} }

推荐答案

您可以使用> c3> 属性,它将产生所需的输出.您无需自己实现Serialize:

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), }

如果您想自己实现Serialize,我相信您想跳过您的变体,因此您不应使用serialize_newtype_variant(),因为它会暴露您的变体.您应该直接使用serialize_str()和serialize_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), } } }

它将产生所需的输出:

{"offset":0}

更多推荐

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

本文发布于:2023-11-06 14:43:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   不包含   情况下   名称   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!