A procedural macro to generate field name enums and constants for structs using Serde, respecting #[serde(rename = "...")] and #[serde(rename_all = "...")].
- Automatically generate a
const SERDE_FIELDS: &'static [&'static str]array containing the serialized names of all non-skipped struct fields. - Generate an enum named
{StructName}SerdeFieldfor all non-skipped fields. - Enum variants match Rust field names (PascalCase) and are annotated with
#[serde(rename = "...")]- matching the field names of the original struct. They're (de)serializable. - Provides convenient methods and trait implementations:
as_str() -> &'static strDisplayimplementationFrom<Enum>andFrom<&Enum>for&'static strTryFrom<&str>andTryFrom<String>with custom errorInvalid{StructName}SerdeFieldFromStrimplementationAsRef<str>for ergonomic usage
- Supports skipped fields via
#[serde(skip)]and renaming via#[serde(rename = "...")]. - Fully respects struct-level
#[serde(rename_all = "...")].
Add this to your Cargo.toml:
[dependencies]
serde = { version = "1.0", features = ["serde_derive"] }
serde_fields = "0.1"use serde::{Serialize, Deserialize};
use serde_fields::SerdeField;
#[derive(Serialize, Deserialize, SerdeField)]
#[serde(rename_all = "camelCase")]
struct User {
user_id: u32,
#[serde(rename = "eMail")]
email: String,
foo_bar: String,
}
// Access serialized field names as a slice
assert_eq!(User::SERDE_FIELDS, &["userId", "eMail", "fooBar"]);
// Use the generated enum
let field = UserSerdeField::UserId;
assert_eq!(field.as_str(), "userId");
assert_eq!(field.to_string(), "userId");
// Parse enum from string
let parsed: UserSerdeField = "userId".parse().unwrap();
assert_eq!(parsed, UserSerdeField::UserId);
// Convert enum to string slice
let name: &str = UserSerdeField::Email.into();
assert_eq!(name, "eMail");
// Serialize
let serialized = serde_json::to_string(&UserSerdeField::FooBar).unwrap();
assert_eq!("\"fooBar\"", serialized);