serde
serde copied to clipboard
Ignore some fields in untagged enum varints
I have an enum struct as this :
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum Message {
Price {
min: BigDecimal,
max: BigDecimal,
}
}
And I have implemented a self-defined serializer for this enum target to insert a new field into the final str. look like this
{
"inserted": "I'm inserted",
"max": "0.1",
"min": "0.1",
}
But in this test case I got an error
fn test_de_after_ser() {
let message = Message::Price{
max: BigDecimal::from_str("0.1").unwrap(),
min: BigDeciaml::from_str("0.1").unwrap(),
};
let serialized = serde_json::to_string(&message).unwrap();
let deserialized: Message = serde_json::from_str(&serialized).unwrap();
}
The runtime complain that could not match any varints in enum, So if there some approach to fix this problem. If not, should we introduce a new attributed like this
#[derive(Debug, Deserialize)]
#[serde(untagged)]
#[serde(ignore = "inserted")]
pub enum Message {
Price {
min: BigDecimal,
max: BigDecimal,
}
}
The attributed #[serde(ignore = "inserted")] semantic is that this contianer should ignore the fields defined in ignore attributed when deserializing from a serialized item.
Extra fields get ignored and it works with other types instead of BigDecimal
. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3cf05e785f0184c3556cce87683eba55
BigDecimal
probably doesn't support deserialization from strings. You can get better error messages if you remove the untagged attribute.
Extra fields get ignored and it works with other types instead of
BigDecimal
. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3cf05e785f0184c3556cce87683eba55BigDecimal
probably doesn't support deserialization from strings. You can get better error messages if you remove the untagged attribute.
But I found that the BigDecimal implemente the Deserialize trait, please tell me why the bigdecimal::BigDecimal could not be ignored ? Maybe I could do some patch for the bigdecimal crate for more wild usage. thx for your reply
I was not able to reproduce this. It deserialized successfully. Assuming fixed in bigdecimal.