我想出了如何在JSON中将一个类似单元的枚举变量序列化为null
,但是有没有一种简单的方法可以将它从null
反序列化,而不必编写专用的反序列化函数?
use serde::{Serialize, Deserialize};
use serde_json::from_str;
#[derive(Serialize, Deserialize)]
struct Entry(String, String);
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Action {
#[serde(serialize_with = "serde::ser::Serializer::serialize_none")]
Delete(),
Create(Entry),
}
type Actions = Vec<Action>;
#[test]
fn this_works() {
from_str::<Actions>(r#"[["id", "value"], []]"#).unwrap();
}
#[test]
fn this_does_not_work() {
// ... but this is what I would like to use
from_str::<Actions>(r#"[["id", "value"], null]"#).unwrap();
}
字符串
参见Rust Playground
1条答案
按热度按时间m1m5dgzv1#
正如@cafce25所指出的,这是预期的:
字符串
试试Rust Playground。