serde
serde copied to clipboard
serde skip will not skip enum values
general:
maybe i did not properly understand the docs, but shouldent #[serde(skip)]
skip an enum field on serializasion?
problem: this code panics
expectation:
ser
should contain the serialized values
without the Container::Empty values
example:
use serde::Serialize;
#[derive(Debug, Serialize)]
#[serde(untagged)]
enum Container {
Value(i64),
Instruction,
#[serde(skip)] // unfortunately this does not work
Empty,
}
#[test]
fn test() {
let values = vec![
Container::Value(1),
Container::Value(2),
Container::Empty,
Container::Value(1),
Container::Empty,
Container::Instruction,
Container::Value(1),
];
let ser = serde_json::to_value(values).expect("damn");
}
The code panics because you are calling expect
on the return value. It is not a panic stemming from serde. If you look at the variant documentation, you can see that this is expected:
Never serialize this variant. Trying to serialize this variant is treated as an error.
With the serde traits, a value cannot decide itself to be skipped. Skipping is only possible if a container (like a sequence, map, struct) decides that it doesn't want to serialize a value. But if serialize
is called on a value, it either needs to serialize something or return an error, which is the case here. You can achieve your goal by writing a custom serialization for the whole Vec
.