Skip to content

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

Open
@brianc118

Description

@brianc118
#[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

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