Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flattened maps with numeric keys do not work correctly. #1638

Closed
tomusdrw opened this issue Sep 23, 2019 · 1 comment
Closed

Flattened maps with numeric keys do not work correctly. #1638

tomusdrw opened this issue Sep 23, 2019 · 1 comment

Comments

@tomusdrw
Copy link

#[derive(serde::Deserialize)]
struct A {
    pub map: std::collections::BTreeMap<u64, String>,
}

#[derive(serde::Deserialize)]
struct B {
    #[serde(flatten)]
    pub map: std::collections::BTreeMap<u64, String>,
}

fn main() {
    // works
    let a: A = serde_json::from_str(r#"{"map": {"1": "a", "2": "b"}}"#).unwrap();
    // fails
    let b: B = serde_json::from_str(r#"{"1": "a", "2": "b"}"#).unwrap();
}

The second call fails with Error("invalid type: string \"1\", expected u64", line: 1, column: 20)'.

Surprisingly (to me) deserializing below struct will fail as well, so it seems it's just enough if the map is nested anywhere in the flattened struct.

#[derive(serde::Deserialize)]
struct C {
    #[serde(flatten)]
    pub map: A,
}
@dtolnay
Copy link
Member

dtolnay commented Jul 5, 2020

The map key conversion from string to number is a serde_json feature so this looks like a special case of #1183. I'll close in favor of that issue.

For a workaround it would be reasonable for a crate such as https://github.com/jonasbb/serde_with to provide the conversion from string keys to numeric keys. Please file a feature request over there if it isn't already supported.

#[derive(Deserialize)]
pub struct B {
    #[serde(flatten, with = "???")]
    map: BTreeMap<u64, String>,
}

@dtolnay dtolnay closed this as completed Jul 5, 2020
dkellner added a commit to dkellner/chronofold that referenced this issue Sep 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants