I would like to deserialize my incoming data from Rocket with Serde with my own deserializer for one field. The tags
field is originally a string and should be deserialized into a Vec<String>
. The format of the string is more-or-less comma-separated values with a special treatment of some characters.
The documentation of Serde is completely unclear for me how to treat that case. The basic structure of tags_deserialize
I just copied from the documentation.
Currently my code is as follows:
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskDataJson {
pub name: String,
pub description: String,
#[serde(deserialize_with = "tags_deserialize")]
pub tags: Vec<String>
}
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
??? - How do I access the string coming from the response and how do I set it??
}
A sample of incoming data is:
{
"name":"name_sample",
"description":"description_sample",
"tags":"tag1,tag2,tag5"
}
where this should lead to:
name = "name_sample";
description = "description_sample"
tags = ["tag1", "tag2", "tag5"]
A workaround is to deserialize the string sequence "tag1,tag2,tag3" as a String
value and then convert it to a Vec
of strings, for example:
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let str_sequence = String::deserialize(deserializer)?;
Ok(str_sequence
.split(',')
.map(|item| item.to_owned())
.collect())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With