给出定义:
#[derive(Serialize, Deserialize)]
enum Bar {
A(i64),
B(u64),
}
#[derive(Serialize, Deserialize)]
struct Foo {
bar: Bar,
}
JSON 序列化
Foo {
bar: Bar::A(123),
}
将是:
{
"bar": "A"
}
最好将属性添加到结构中的字段而不是枚举定义中(枚举将在值也需要序列化的结构字段中重用)
#[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"}
如果无法修改
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"}