簡體   English   中英

Rust/Serde:將外部結構序列化為 json 駝峰式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM