Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom rename_all property for serde?

Tags:

rust

serde

So being new to Rust, I had a need to deserialize json from "title case" format to snake case (e.g., {"Car Prop": 1, "Door Prop": 2}). The serde library in Rust seems to provide every common format except for this - https://serde.rs/container-attrs.html.

1) What is this bit of code called #[serde(rename_all = "...")] ? Is that a reference to a macro rule? And if so where in the serde code might I go looking for it?

2) How would I implement my own custom "container attr" to do the deserialize from "title case" json to a struct with properties in snake_case? I realize that could be quite involved so even an answer to 1 to get me pointed in the right direction would be a great help, thanks.

like image 894
Nona Avatar asked Dec 23 '25 02:12

Nona


1 Answers

As far as I'm aware adding additional rename rules is not possible at the moment. As to your first question, yes it is a macro. If you look at the serde_derive code, you will see that the macro uses RenameRule which is an enum with all the available rename rules.

So you may not be able to use the serde macros to achieve what you want, but you can write your own serialization and deserialization code instead. So instead of having the macro generate it, you write it yourself.

A custom serializer would look something like this:

#[derive(Debug)]
struct Message {
    foo_bar: String,
    bar_foo: String
}

impl Serialize for Message {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
        S: Serializer {
        let mut state = serializer.serialize_struct("Message", 1)?;
        state.serialize_field("Foo Bar", &self.foo_bar)?;
        state.serialize_field("Bar Foo", &self.bar_foo)?;
        state.end()
    }
}

Creating the deserializer is a bit more involving, but the serde documentation provides an example here: Manually implementing Deserialize for a struct.

I created a full working example here: rust playground

like image 179
user1516867 Avatar answered Dec 27 '25 14:12

user1516867



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!