json icon indicating copy to clipboard operation
json copied to clipboard

Bug: untagged union fails to deserialize hashmap with usize as keys

Open odesenfans opened this issue 2 years ago • 0 comments

Hello,

I think I found an issue related to the deserialization of hashmaps in an untagged enum. I have a struct that contains a HashMap<usize, usize>:

#[derive(Deserialize, Debug)]
struct T {
    h: HashMap<usize, usize>,
}

This struct is used in an enum and I want to deserialize to that enum type:

#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum E {
    T(T),
    // Other variants omitted
}

My problem is the following. When deserializing an example, deserializing to T works but deserializing to E fails. This appears to be due to the fact that the untagged enum deserializer does not make the connection between the string keys and the usize keys of the hashmap. However, iirc, following the JSON standard keys should always be strings.

#[test]
fn test_serde_untagged() {
    let s = "{\"h\": {\"1\": 2, \"3\": 4}}";

    // Works
    let t: T = serde_json::from_str(s).unwrap();
    println!("{:?}", t);
    
    // Fails
    let e: E = serde_json::from_str(s).unwrap();
    println!("{:?}", e);
}

Is this a known issue? Am I missing something?

odesenfans avatar Jan 10 '24 14:01 odesenfans