Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
joriwind opened this issue Mar 5, 2025 · 1 comment
Open

Comments

@joriwind
Copy link

joriwind commented Mar 5, 2025

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);
}
@jonasbb
Copy link
Contributor

jonasbb commented Mar 5, 2025

This is one example caused by #1183

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants