Rust 在 JSON 序列化时复用结构体字段

依赖

toml 复制代码
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }

示例

参考 https://serde.rs/attr-flatten.html

rust 复制代码
#[derive(serde::Serialize, serde::Deserialize, Debug, Copy, Clone)]
#[serde(rename_all(serialize = "camelCase", deserialize = "camelCase"))]
pub struct PageRequest {
    pub page: i32,
    pub size: i32,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all(serialize = "camelCase", deserialize = "camelCase"))]
pub struct PageResponse<T> {
    #[serde(flatten)]
    page_request: PageRequest,
    total: i64,
    content: Vec<T>,
}

impl Default for PageRequest {
    fn default() -> Self {
        Self { page: 1, size: 10 }
    }
}

fn main() {
    // language=json
    let json = r#"{ "page": 1, "size": 5, "total": 100, "content": [1, 2, 3, 4, 5] }"#;

    let page_response = serde_json::from_str::<PageResponse<i32>>(json).unwrap();
    println!("{page_response:?}");

    let json = serde_json::to_string_pretty(&page_response).unwrap();
    println!("{json}")
}
相关推荐
朝阳58110 小时前
用 Rust + Actix-Web 打造“Hello, WebSocket!”——从握手到回声,只需 50 行代码
前端·websocket·rust
中国胖子风清扬14 小时前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
我就是全世界14 小时前
【存储选型终极指南】RustFS vs MinIO:5大维度深度对决,95%技术团队的选择秘密!
开发语言·分布式·rust·存储
微笑伴你而行16 小时前
目标检测如何将同时有方形框和旋转框的json/xml标注转为txt格式
xml·目标检测·json
cdcdhj17 小时前
数据库存储大量的json文件怎么样高效的读取和分页,利用文件缓存办法不占用内存
缓存·node.js·json
Source.Liu18 小时前
【Python基础】 13 Rust 与 Python 注释对比笔记
开发语言·笔记·python·rust
Source.Liu1 天前
【Python基础】 19 Rust 与 Python if 语句对比笔记
笔记·python·rust
Source.Liu1 天前
【Python基础】 18 Rust 与 Python print 函数完整对比笔记
笔记·python·rust
Z_z在努力1 天前
【杂类】JSON:现代Web开发的数据交换基石
json
学渣676561 天前
文件传输工具rsync|rust开发环境安装|Ascend实验相关命令
开发语言·后端·rust