Search code examples
rustserde

Can I serialize a struct camel_case and deserialize PascalCase in Rust


I have a struct I want to be able to serialize in camel_case and deserialize in PascalCase. Is this possible? I've seen the serde rename_all = snake_case


Solution

  • From the docs:

    #[serde(rename_all = "...")]

    Rename all the fields (if this is a struct) or variants (if this is an enum) according to the given case convention. The possible values are "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE".

    Allows specifying independent cases for serialization vs deserialization:

    • #[serde(rename_all(serialize = "..."))]
    • #[serde(rename_all(deserialize = "..."))]
    • #[serde(rename_all(serialize = "...", deserialize = "..."))

    So #[serde(rename_all(serialize = "camelCase", deserialize = "PascalCase"))]