serde icon indicating copy to clipboard operation
serde copied to clipboard

HashMap will not deserialize if the enum "tag" is set to "type"

Open inoutch opened this issue 2 years ago • 1 comments

I get an error executing the following code.

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

#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Enum {
    A { h: HashMap<u32, String> },
}

fn main() {
    let mut h = HashMap::new();
    h.insert(123, "Hello".to_string());

    let e = Enum::A { h };
    let str = serde_json::to_string(&e).unwrap();
    let _: Enum = serde_json::from_str(&str).unwrap(); // <-- Error occurred here!
}

The error message is as follows:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: string \"123\", expected u32", line: 0, column: 0)',

This code seems to work well if I remove the serde(tag = "type"). Is this a bug?

Environment

  • serde: 1.0.136
  • serde_json: 1.0.78
  • cargo 1.54.0-nightly (0cecbd673 2021-06-01)

inoutch avatar Jan 31 '22 16:01 inoutch

Yes, this is duplicate of #1183

Mingun avatar Jan 31 '22 20:01 Mingun