依赖
toml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
示例
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}")
}