Reputation: 51
I need to convert case from keys of json data while processing just the fields I need (I just need some parts of the json data). The conversion of case will be from snake to camel and vice versa.
I tried to do the following:
Let's suppose that we have this struct and that I derive the necessary serde traits:
struct ParentSnakeToCamel {
first_data: A,
second_data: B,
}
struct ParentCamelToSnake {
first_data: A,
second_data: B,
}
struct A {
field_one: String,
field_two: Option<u32>,
}
struct B {
field_three: Option<bool>,
field_four: String,
}
I tried to apply the rename_all attribute of serde to see if it spreads to the inner structs:
#[serde(rename_all(deserialize = "snake_case", serialize = "camelCase"]
struct ParentSnakeToCamel {...}
#[serde(rename_all(deserialize = "camelCase", serialize = "snake_case"]
struct ParentCamelToSnake {...}
So, whenever I need to parse a json from snake to camel I would use ParentSnakeToCamel struct and if I need to parse from camel to case I would use ParentCamelToSnake.
But rename_all doesn't spread to the inner structs.
What could I do? The only way I see to accomplish that is to duplicate the inner structs to be able to apply rename_all to the inner structs fields according to the case I need to parse. In other words, to create something like ACamel, BCamel, ASnake, BSnake and link to its correspondent parent struct. I believe that's an ugly hack :(
Thanks for your help.
Upvotes: 5
Views: 1920