Skip to content
badlopoPublic

About

区分 JSON 字段「不存在 / null / 有值」的三态类型,配合 serde 使用。

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tres

区分 JSON 字段「不存在 / null / 有值」的三态类型,配合 serde 使用。

状态 序列化 反序列化
Tres::Absent 跳过该字段 字段缺失
Tres::Null null 字段为 null
Tres::Value(T) 正常序列化 T 字段有值

引入

[dependencies]
tres = { git = "https://github.com/badlopo/tres-rs.git" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

用法

结构体上需要加 #[tres_object],才能正确处理 Absent(跳过序列化 / 缺失反序列化为 Absent):

use serde::{Deserialize, Serialize};
use tres::{Tres, tres_object};

#[tres_object]
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct {
    absent: Tres<String>,
    null: Tres<String>,
    value: Tres<String>,
}

fn main() {
    let obj = MyStruct {
        absent: Tres::Absent,
        null: Tres::Null,
        value: Tres::Value("hello".into()),
    };

    // => {"null":null,"value":"hello"}
    println!("{}", serde_json::to_string(&obj).unwrap());

    let json = r#"{"null":null,"value":"hello"}"#;
    let obj: MyStruct = serde_json::from_str(json).unwrap();
    // absent == Absent, null == Null, value == Value("hello")
    println!("{:?}", obj);
}

若类型别名不是 Tres,通过 tres_name 指定:

use tres::{Tres as MyTres, tres_object};

#[tres_object(tres_name = "MyTres")]
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct {
    field: MyTres<String>,
}

About

区分 JSON 字段「不存在 / null / 有值」的三态类型,配合 serde 使用。

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages