Serde: Automatically convert from camelCase to snake_case

Created on 3 Mar 2017  路  2Comments  路  Source: serde-rs/serde

Frequently json formats use camelCase and creating structs that match them makes rust compiler complain that it is not snake_case.

Currently when I have a json like:

{
    "importantNumber": 123.03
}

I need to create following struct:

#[derive(Serialize, Deserialize)]
struct Foo {
   importantNumber: f64
}

I would prefer to have:

#[derive(Serialize, Deserialize)]
#[serde(to_snake_case=true)]
struct Foo {
   important_number: f64
}

This is somehow similar to #13 (which is a workaround for this issue), but if there are many fields it becomes cumbersome and highly unreadable.

support

Most helpful comment

Check out the rename_all attribute here.

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Foo {
    important_number: u32
}

All 2 comments

Check out the rename_all attribute here.

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Foo {
    important_number: u32
}

Oops, I didn't notice that one, thanks.

Was this page helpful?
0 / 5 - 0 ratings