Skip to content

Error deserializing tagged enum containing map with integer keys #1254

Open
@manforowicz

Description

@manforowicz

I get a runtime error when trying to deserialize a tagged enum that contains a map with integer keys. Here's a reproducible example:

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Msg {
    Map { map: BTreeMap<i32, i32> },
}

fn main() {
    let msg = Msg::Map {
        map: [(1, 2), (3, 4)].into(),
    };

    let serialized = serde_json::to_string_pretty(&msg).unwrap();
    println!("Serialized:\n{serialized}");

    let _received: Msg = serde_json::from_str(&serialized).unwrap();
}

It panics with:

Error("invalid type: string \"1\", expected i32", line: 0, column: 0)

Playground link.

However, I don't get an error when I remove the #[serde(tag = "type")], or when I use non-integer keys. Is this expected behavior?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions