rust 从/到空序列化

yzuktlbb  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(169)

我想出了如何在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

m1m5dgzv

m1m5dgzv1#

正如@cafce25所指出的,这是预期的:

use serde::{Serialize, Deserialize};
use serde_json::from_str;

#[derive(Serialize, Deserialize)]
struct Entry(String, String);

#[derive(Serialize, Deserialize, Default)]
#[serde(untagged)]
enum Action {
    #[default]
    Delete,
    Create(Entry),
}
type Actions = Vec<Action>;

#[test]
fn works() {
  from_str::<Actions>(r#"[["id", "value"], null]"#).unwrap();
}

字符串
试试Rust Playground

相关问题