#serialization #unit #deserialize #derive-deserialize #struct #no-alloc #serde-unit-struct

no-std serde_unit_struct_derive

serde_unit_struct的proc-macro引擎

3个版本

0.1.3 2023年12月16日
0.1.2 2023年11月8日
0.1.1 2022年4月15日
0.1.0 2022年3月1日

#59 in #derive-deserialize

Download history 661/week @ 2024-03-14 752/week @ 2024-03-21 722/week @ 2024-03-28 1203/week @ 2024-04-04 795/week @ 2024-04-11 736/week @ 2024-04-18 967/week @ 2024-04-25 762/week @ 2024-05-02 764/week @ 2024-05-09 560/week @ 2024-05-16 959/week @ 2024-05-23 875/week @ 2024-05-30 986/week @ 2024-06-06 1107/week @ 2024-06-13 768/week @ 2024-06-20 597/week @ 2024-06-27

3,609 每月下载量
2 个crate中使用 (通过 serde_unit_struct)

MIT/Apache

6KB
53 代码行,不含注释

Serde Unit Struct Derive

此crate为Serde的SerializeDeserialize 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.0MIT license许可。

除非您明确声明,否则您有意提交给此crate的任何贡献,根据Apache-2.0许可定义,应如上所述双重许可,不附加任何额外条款或条件。

依赖关系

~315–770KB
~18K SLoC