serde icon indicating copy to clipboard operation
serde copied to clipboard

allow `#[serde(other)]` on `enum`s with `#[serde(untagged)]` ?

Open midnightexigent opened this issue 4 years ago • 1 comments

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), 
}

midnightexigent avatar Jul 13 '21 21:07 midnightexigent

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}]

Source


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.

jonasbb avatar Jul 13 '21 22:07 jonasbb