serde
serde copied to clipboard
allow `#[serde(other)]` on `enum`s with `#[serde(untagged)]` ?
any reason why we can't write something like ?
#[derive(Deserialize)]
#[serde(untagged)]
struct Foo {
Bar(Bar),
...
#[serde(other)]
Fallback, // literally nobody cares about what data the user tried to pass in
}
Note: the same thing could be accomplished by some sort of no-op Deserialize that never fails
#[derive(Deserialize)]
#[serde(untagged)]
struct Foo {
Bar(Bar),
...
Fallback(Noop),
}
While I do not know why the derive does not allow this, you can quite easily "simulate" it:
use serde_with::rust::deserialize_ignore_any;
#[derive(Deserialize)]
#[serde(untagged)]
enum Item {
Foo{x: u8},
#[serde(deserialize_with = "deserialize_ignore_any")]
Other,
}
// Deserialize this JSON
json!([
{"y": 1},
{"x": 1},
])
// into these Items
vec![Item::Other, Item::Foo{x: 1}]
Note: the same thing could be accomplished by some sort of no-op Deserialize that never fails
The serde::de::IgnoredAny type provides exactly this functionality. It can always be deserialized and will never error on any input.