Expand description
§json2struct: Compile-Time Struct Generation
A powerful procedural macro for generating Rust structs from JSON-like structures with extensive compile-time type safety and configuration options.
§Features
- Automatic struct generation from JSON-like syntax
- Flexible type inference
- Serde integration
- Compile-time type checking
- Multiple configuration flags
§Basic Usage
// Simple struct generation
json2struct!(User {
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
});
§Output
#[derive(Clone, Deserialize, Serialize)]
struct User {
#[serde(alias = "first_name")]
first_name: String,
#[serde(alias = "last_name")]
last_name: String,
#[serde(alias = "age")]
age: f64
}
§Example with Flags
// Complex struct with multiple configurations
json2struct!(Company @debug @camel @derive(PartialEq) @store_json {
"company_name" => "Acme Corp",
"employees" => [
{
"id" => 1,
"details" => {
"email" => "john@example.com",
"department" => "Engineering"
}
}
]
});
§Output
static COMPANY_JSON_VALUE: LazyLock<Value> = LazyLock::new(||
{
::serde_json::from_str(
"{\"company_name\":\"Acme Corp\",\"employees\":[{\"details\":{\"department\":\"Engineering\",\"email\":\"john@example.
com\"},\"id\":1.0}]}",
)
.expect("Couldn't convert the text into valid json")
});
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct Company {
#[serde(alias = "company_name")]
company_name: String,
#[serde(alias = "last_name")]
employees: CompanyEmplyees
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CompanyEmplyees {
#[serde(alias = "id")]
id: f64,
#[serde(alias = "details")]
details:
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CompanyEmplyeesDetails {
#[serde(alias = "email")]
email: String,
#[serde(alias = "department")]
department: String
}
§Supported Flags
Flag | Description | Example |
---|---|---|
@debug | Adds Debug derive | @debug |
@snake | Renames fields to snake_case | @snake |
@camel | Renames fields to camelCase | @camel |
@pascal | Renames fields to pascal | @pascal |
@derive(Type) | Adds custom derives | @derive(PartialEq, Clone) |
@store_json | Generates a static JSON Value constant | @store_json |
Macros§
- json2struct
- json2struct: Generates Rust structs from JSON-like structures