3个版本
0.1.3 | 2023年12月16日 |
---|---|
0.1.2 |
|
0.1.1 | 2022年4月15日 |
0.1.0 | 2022年3月1日 |
#59 in #derive-deserialize
3,609 每月下载量
在 2 个crate中使用 (通过 serde_unit_struct)
6KB
53 代码行,不含注释
Serde Unit Struct Derive
此crate为Serde的Serialize
和Deserialize
traits提供derive宏,使得单元结构体以字符串形式表示其名称。如果您想保留类型信息,即区分不同的单元结构体,这很有用。
没有serde_unit_struct
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct Foo;
#[derive(Deserialize, Serialize)]
struct Bar;
fn main() {
// Normally, unit structs serialize to null.
let json = serde_json::to_string(&Foo).unwrap();
assert_eq!(json, "null");
// We can successfully deserialize them, but...
let foo: Foo = serde_json::from_str(&json).unwrap();
assert_eq!(foo, Foo);
// ...this also works; the type information is lost.
let bar: Bar = serde_json::from_str(&json).unwrap();
assert_eq!(bar, Bar);
}
使用serde_unit_struct
use serde_unit_struct::{Deserialize_unit_struct, Serialize_unit_struct};
#[derive(Deserialize_unit_struct, Serialize_unit_struct)]
struct Foo;
#[derive(Deserialize_unit_struct, Serialize_unit_struct)]
struct Bar;
fn main() {
// Now, unit structs serialise to their name as a string.
let json = serde_json::to_string(&Foo).unwrap();
assert_eq!(json, "\"Foo\"");
// We can successfully deserialize them.
let foo: Foo = serde_json::from_str(&json).unwrap();
assert_eq!(foo, Foo);
// Type information is maintained.
let bar: Result<Bar, _> = serde_json::from_str(&json);
assert!(bar.is_err());
}
许可
根据您的选择,受Apache License, Version 2.0或MIT license许可。
除非您明确声明,否则您有意提交给此crate的任何贡献,根据Apache-2.0许可定义,应如上所述双重许可,不附加任何额外条款或条件。
依赖关系
~315–770KB
~18K SLoC