[英]How to serialise only name of variant and ignore value for enum field in struct (serde)
Given the definitions:给定定义:
#[derive(Serialize, Deserialize)]
enum Bar {
A(i64),
B(u64),
}
#[derive(Serialize, Deserialize)]
struct Foo {
bar: Bar,
}
the JSON serialisation for JSON 序列化为
Foo {
bar: Bar::A(123),
}
would be:将会:
{
"bar": "A"
}
It would be ideal to add an attribute to the field in the struct instead of inside the enum definition (the enum will be reused in a struct field where the value needs to be serialised too)将属性添加到结构中的字段而不是枚举定义中是理想的(枚举将在值也需要序列化的结构字段中重用)
The attribute #[serde(skip)]
can be used on tuple variant fields:属性
#[serde(skip)]
可用于元组变量字段:
use serde::{Serialize, Deserialize}; // 1.0.126
use serde_json; // 1.0.64
#[derive(Serialize, Deserialize)]
enum Bar {
A(#[serde(skip)] i64),
B(#[serde(skip)] u64),
}
#[derive(Serialize, Deserialize)]
struct Foo {
bar: Bar,
}
fn main() {
let foo = Foo { bar: Bar::A(123) };
println!("{}", serde_json::to_string(&foo).unwrap());
}
{"bar":"A"}
If modifying Bar
isn't an option, you'll have to do it a bit more manually via #[serde(with =...)]
or #[serde(serialize_with =...)]
:如果修改
Bar
不是一个选项,您必须通过#[serde(with =...)]
或#[serde(serialize_with =...)]
手动进行一些操作:
use serde::{Serialize, Deserialize, ser::Serializer}; // 1.0.126
use serde_json; // 1.0.64
#[derive(Serialize, Deserialize)]
enum Bar {
A(i64),
B(u64),
}
#[derive(Serialize, Deserialize)]
struct Foo {
#[serde(serialize_with = "bar_name_only")]
bar: Bar,
}
fn bar_name_only<S>(bar: &Bar, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let name = match bar {
Bar::A(_) => "A",
Bar::B(_) => "B",
};
serializer.serialize_str(name)
}
fn main() {
let foo = Foo { bar: Bar::A(123) };
println!("{}", serde_json::to_string(&foo).unwrap());
}
{"bar":"A"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.