I need help with my Rust project where I’m connecting to an external API that requires data in HashMap format with specific property types.
I want to avoid writing the same conversion code over and over again. Instead, I’d like to use custom attributes on my struct fields to automatically generate the right format.
Here’s what I’m trying to achieve with a struct like this:
#[derive(Serialize, Deserialize)]
struct Employee {
#[api_field(property = "title", label = "Full Name")]
pub full_name: String,
#[api_field(property = "url", label = "Profile Picture")]
pub avatar_url: Option<String>,
#[api_field(property = "MultiSelect", label = "Skills")]
pub skill_list: Option<Vec<serde_json::Value>>,
}
I want this to automatically convert into something like:
let mut result = HashMap::new();
result.insert("Full Name".to_string(), ApiProperty::Title(
vec![
TextContent {
formatting: None,
content_type: Some(TextType::Plain),
formula: None,
reference: None,
display_text: None,
link: None,
text_data: TextData {
value: employee.full_name.clone(),
url: None
}
}
]
));
if let Some(avatar) = employee.avatar_url.clone() {
result.insert("Profile Picture".to_string(), ApiProperty::Url(avatar));
}
result.insert("Skills".to_string(), ApiProperty::MultiSelect(
employee.skill_list.iter().map(|item| SelectItem {
identifier: None,
theme: None,
title: format!("{}", item)
}).collect()
));
How can I implement this kind of automatic conversion using procedural macros or derive macros in Rust?