Rust/Serde:将外部结构序列化为 json camelcase

gsu*_*erg 5 json rust serde

我正在编写一些代码,这些代码采用外部库返回的结构,将其序列化为 json,并使用pbjson. 外部库使用 serde 和 Implements Serialize,但返回的 json 是蛇形格式。问题是pbjson期望 json 是驼峰式的。

如何获取 serde json 对象的驼峰版本?(即配置外部库以使用类似的东西#[serde(rename_all = "camelCase")]或将 json 键转换为驼峰式?)

注意:我正在处理许多远程结构,总共有近 2k 行代码。如果可能的话,我想避免在本地重新创建这些类型。

Bal*_*Ben 2

如果我理解正确的话,你想要这样的东西吗?基本上,您只需将外来项目转换为您自己类型的项目,然后将其序列化即可。

// 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"}]
}
Run Code Online (Sandbox Code Playgroud)