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

#[serde(flatten)] on BTreeMap<String, Value> does not capture unknown/remaining fields #2176

Open
brianc118 opened this issue Feb 18, 2022 · 0 comments

Comments

@brianc118
Copy link

brianc118 commented Feb 18, 2022

#[derive(PartialEq, Debug, Serialize, Deserialize)]
struct Inner {
    a: u32,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
struct Outer {
    #[serde(flatten)]
    i: Inner,
    b: u32,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
struct OuterWithExtra {
    #[serde(flatten)]
    outer: Outer,
    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

Based on https://serde.rs/attr-flatten.html#capture-additional-fields and example usage in #1179 I assumed that having a flattened other: HashMap<String, Value> at the end of a struct to be deserialized into will always return us unknown fields. In the above example, deserializing into OuterWithExtra gives us all fields that are supplied in the JSON, while also setting a and b correctly. This doesn't seem like the desired behavior?

If we don't have nested #[serde(flatten)] it behaves as expected. See playground.

I was exploring this as a way to detect unknown fields after finding that serde_ignored doesn't work with #[serde(flatten)]: dtolnay/serde-ignored#10

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

1 participant