serde
serde copied to clipboard
#[serde(flatten)] on BTreeMap<String, Value> does not capture unknown/remaining fields
#[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)]
: https://github.com/dtolnay/serde-ignored/issues/10