Skip to content

#[serde(rename_all = ...)] and #[serde(flatten)] #2916

Open
@neumann-paulmann

Description

@neumann-paulmann

Currently, newtype-wrapping an existing struct to change its naming scheme does not work:

use serde::{Deserialize, Serialize};
use serde_json; // 1.0.140

mod other_crate {
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct Foo {
        does_frobnicate: bool,
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MyFoo {
    #[serde(flatten)]
    inner: other_crate::Foo,
}

fn main() {
    let foo = other_crate::Foo::default();
    let s = serde_json::to_string(&foo).unwrap();
    assert_eq!(s, r#"{"does_frobnicate":false}"#);

    let my_foo = MyFoo::default();
    let my_s = serde_json::to_string(&my_foo).unwrap();
    assert_eq!(my_s, r#"{"doesFrobnicate":false}"#);
}

Playground

While I understand that changing this to the outcome, which I would expect could break existing user code, I suggest adding #[serde(rename_all = ...)] as a field attribute as well if and only if applied to a #[flatten]ed field.
This should apply recursively to all potentially nested structs withingthe flattened struct.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions