[英]Rust/Serde: serialize external struct to json camelcase
我正在处理一些代码,这些代码采用外部库返回的结构,将其序列化为 json,并使用pbjson
将 json 序列化为 protobuf。 外部库使用 serde 并实现了Serialize
,但返回的 json 是蛇案例。 问题是 pbjson 期望pbjson
是驼峰式的。
如何获得 serde json object 的驼峰版本? (即配置外部库使用类似#[serde(rename_all = "camelCase")]
或将 json 密钥转换为驼峰式?)
注意:我正在使用许多远程结构,它们总共加起来将近 2k 行代码。 如果可能,我想避免在本地重新创建这些类型。
如果我理解正确,你想要这样的东西吗? 基本上,您只需要将外来项目变成您自己类型的项目,然后将它们序列化。
// foreign struct
#[derive(Serialize, Deserialize)]
struct Foreign {
the_first_field: u32,
the_second_field: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Mine {
the_first_field: u32,
the_second_field: String,
}
impl From<Foreign> for Mine {
fn from(
Foreign {
the_first_field,
the_second_field,
}: Foreign,
) -> Self {
Self {
the_first_field,
the_second_field,
}
}
}
fn main() {
// only used to construct the foreign items
let in_json = r#"[{"the_first_field": 1, "the_second_field": "second"}]"#;
let foreign_items = serde_json::from_str::<Vec<Foreign>>(in_json).unwrap();
let mine_items = foreign_items.into_iter().map(Mine::from).collect::<Vec<_>>();
let out_json = serde_json::to_string(&mine_items).unwrap();
println!("{}", out_json); // [{"theFirstField":1,"theSecondField":"second"}]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.