serde icon indicating copy to clipboard operation
serde copied to clipboard

Failure to deserialize key as integer when wrapped in a tagged enum

Open joriwind opened this issue 8 months ago • 1 comments

I encountered an issue where serde fails to deserialize a key as an integer when it is wrapped in a tagged enum. I was able to create a minimal code example, see below. The deserialization results in the following error: Error("invalid type: string \"5\", expected u8", line: 0, column: 0). The code example works when the #[serde(tag = "type")] attribute is removed from the enum. The serialized output is {"type":"Full","param":{"5":2}}.

use serde_json; // 1.0.138
use serde::{Serialize, Deserialize}; // 1.0.217
use std::collections::BTreeMap;

#[derive(Debug, Deserialize, Serialize)]
struct Test {
    param: BTreeMap<u8, u8>,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
enum Wrapper {
    Full(Test),
}

impl Default for Test {
    fn default() -> Self {
        let mut param = BTreeMap::new();
        param.insert(5, 2);
        
        Self {
            param
        }
    }
}


fn main() {
    let value = Wrapper::Full(Test::default());
    let output = serde_json::to_string(&value).unwrap();
    println!("{}", output);
    let after: Wrapper = serde_json::from_str(&output).unwrap();
    println!("{:?}", after);
}

joriwind avatar Mar 05 '25 15:03 joriwind

This is one example caused by https://github.com/serde-rs/serde/issues/1183

jonasbb avatar Mar 05 '25 17:03 jonasbb