介绍

Serde是一个Rust的高效且通用的序列化和反序列化框架.

Serde利用的Rust的trait系统来去实现了数据结构的序列化和反序列化.而不是像其他语言一样利用运行时反射.

引入依赖

<!-- Cargo.toml -->
[dependencies]
serde = { version = "1.0", features = ["derive"] }
# serde_json is just for the example, not required in general
serde_json = "1.0"

序列化和反序列化

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}
fn main() {
    let point = Point { x: 1, y: 2 };

    //Struct转为JSON
    let serialized = serde_json::to_string(&point).unwrap();
    println!("serialized = {}", serialized);

    //JSON转为Struct
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();
    println!("deserialized = {:?}", deserialized);

    //JSON转为Value
    let deserialized: Value = serde_json::from_str(&serialized).unwrap();
    println!("deserialized = {:?}", deserialized);
}

常用属性attributes

see https://serde.rs/attributes.html

设置field默认值

#[derive(Serialize, Deserialize, Debug,Default)]
#[serde(default)]
struct Point {
    x: i32,
    y: i32,
}

属性field转camelCase

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Person {
    first_name: String,
    last_name: String,
}

跳过不需要的field

#[derive(Serialize)]
struct Resource {
    // Always serialized.
    name: String,

    // Never serialized.
    #[serde(skip_serializing)]
    hash: String,

    // Use a method to decide whether the field should be skipped.
    #[serde(skip_serializing_if = "Map::is_empty")]
    metadata: Map<String, String>,
}