I'm having a hard time understanding how to implement deserialize for a custom mapping using Rust's serde. I'd be glad if someone could help me with this example:
I've got the following struct:
#[derive(Debug, Clone, PartialEq)]
pub struct ConnectorTopics {
pub name: String,
pub topics: Vec<String>,
}
And the JSON data comes in the following format:
{
"test-name": {
"topics": [
"topic1",
"topic2"
]
}
}
As you can see, name field is a wrapper for the topics, so in my case this should deserialize to:
let _ = ConnectorTopics {
name: "test-name".into(),
topics: vec!["topic1".into(), "topic2".into()]
}
My first attempt was to use a custom structure inside Deserialize implementation, however, that wouldn't compile and doesn't seem to be the correct approach.
impl<'de> Deserialize<'de> for ConnectorTopics {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Debug, Deserialize)]
struct Inner {
topics: Vec<String>,
}
let a = deserializer.deserialize_map(HashMap<String, Inner>).unwrap();
let value = Deserialize::deserialize::<HashMap<String, Inner>>(deserializer)?;
let (connector, inner) = value.iter().nth(0).ok_or("invalid")?.0;
Ok(ConnectorTopics {
name: connector,
topics: vec![],
})
}
}