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}")
}
相关推荐
离歌漠20 小时前
《我用 Tauri 做了一个本地开发工具箱》
rust·typescript·vue
小小龙学IT1 天前
Python Polars 高性能数据处理引擎深度解析
开发语言·python·rust·1024程序员节
zzu123zsw1 天前
为什么 Python 做 Agent 总在并发中崩溃?拆解 Blockcell 在 Rust 下的 Host-Cell 隔离与自愈状态机
开发语言·python·rust·大模型·ai agent
hsg771 天前
简述:基于Ubuntu24编译发布rust开发的html+web后端服务的方法
rust·1024程序员节
zzu123zsw1 天前
当 GPU 加速渲染遇上无头组件:拆解 Yororen UI 在 GPUI 生态下的状态解耦与 XML 模板实践
xml·ui·rust·gui·gpui
传奇开心果编程2 天前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
本地化文档2 天前
cutile-rs-book-l10n
rust·gpu·nvidia·cuda·sphinx·crowdin
qq_406981032 天前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust
康小旺2 天前
TypeScript 编译器开始卷 Rust 了:Cloudflare 的 tsrs 到底想干嘛?
rust·typescript
Norna2 天前
时间轮的 +1,为什么最后只留在顶层
rust