'Cant serialize when using enum as key in Hashmap
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Demo {
#[serde(with = "serde_with::json::nested")]
pub something: HashMap<Option<Resource>, bool>,
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Eq, Hash)]
pub enum Resource {
#[serde(rename = "cpu")]
Cpu,
#[serde(rename = "memory")]
Memory,
}
I am using an Enum property "Resource" as my hashmap key. Now, I want to send my data to an HTTP endpoint, so I want to serialize the data. This is how I did it :
let mut something = HashMap::new();
something.insert(Some(Cpu), true);
let data = Demo{
something: something,
};
let serialized = serde_json::to_string(&data).unwrap();
println!("serialized {}", serialized);
But, the to_string is failing saying ==> Error("key must be a string", line: 0, column: 0)
can I map my enum values to be string at the time of serialization ? How to solve this ?
Solution 1:[1]
You can use different annotations from serde_with to make your example work. The problem how you used serde_with::json::nested is that it converts the whole HashMap into a String, which fails, because the keys do not serialize as strings. If you apply the attribute only to the key part, it works.
#[serde_with::serde_as]
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Demo {
#[serde_as(as = "HashMap<serde_with::json::JsonString, _>")]
pub something: HashMap<Option<Resource>, bool>,
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jonasbb |
