I want to avoid code repetition as much as possible.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize, Debug)]
enum AttibuteType {
#[serde(rename = "ID")]
Id,
#[serde(rename = "STRING")]
String,
#[serde(rename = "BOOL")]
Bool,
#[serde(rename = "NUMERIC")]
Numeric,
#[serde(rename = "ARRAY")]
Array
}
#[derive(Serialize, Deserialize, Debug)]
struct Attribute {
name: String,
#[serde(rename(deserialize = "dataType"))]
attribute_type: AttibuteType,
#[serde(rename(deserialize = "of"))]
array_attribute_type: Option<String>
}
fn typed_example() -> Result<()> {
let data = r#"
{
"name": "John Doe",
"dataType": "ID",
"of" : "STRING"
}"#;
let p: Attribute = serde_json::from_str(data)?;
println!("{:?}", p);
Ok(())
}
fn main() {
typed_example().unwrap();
}
I cannot change, at this stage of the project, the data that are being sent (names, values etc.), so I decided to rename and manipulate them in Rust. I am not sure if I am going to the correct direction by using all those rename tags for enums. Currently the "client" sends some strings, all capital. I want to be sure that my Rust server accepts only those values (ID, STRING, BOOL, NUMERIC, ARRAY). Is the definition of AttributeType
above adequate to satisfy that need?
Is there any other more elegant way instead of using rename to each enum value to ask from serde to make all values PascalCase?