JSON to Rust Struct Generator
Convert JSON schemas into idiomatic Rust structs with Serde Serialize and Deserialize derive macros.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is JSON to Rust Struct Generation?
JSON to Rust Struct Generation transforms arbitrary JavaScript Object Notation (JSON) payloads into strongly typed, memory-safe Rust struct definitions powered by the industry-standard Serde framework (serde, serde_json). In high-performance backend systems—such as microservices running on Axum, Actix-web, or Tonic (gRPC), CLI utilities, and blockchain runtimes (like Solana and Polkadot)—Rust is chosen for its zero-cost abstractions, thread safety, and lack of a garbage collector.
However, Rust's strict static type system requires every incoming data field to have an explicit type. Manually writing nested Rust structs—while accounting for Rust's strict snake_case identifier conventions, wrapping nullable JSON fields in Option<T>, and applying Serde macro attributes—is time-consuming and tedious.
The Affi-Chain JSON to Rust Struct Generator analyzes complex JSON trees, generates idiomatic Rust structs with #[derive(Serialize, Deserialize)], handles field renames, maps vectors and nested sub-structs, and outputs clean, production-ready Rust code directly in your browser with 0ms latency.
The Serde Attribute & Type Mapping Matrix
The Serde ecosystem provides compile-time derive macros that generate optimized, reflection-free serialization code:
| Serde Attribute | Rust Syntax Pattern | Architectural Purpose & Behavior |
|---|---|---|
#[derive(Serialize, Deserialize)] | Struct annotation | Auto-generates high-throughput serialization and deserialization trait implementations |
#[serde(rename_all = "camelCase")] | Container attribute | Automatically translates all JSON camelCase keys into Rust snake_case fields |
#[serde(rename = "...")] | Field attribute | Explicitly renames individual fields that violate Rust naming rules or keyword collisions |
#[serde(default)] | Field attribute | Falls back to Default::default() if the key is missing from incoming JSON |
#[serde(skip_serializing_if = "...")] | Field attribute | Excludes None fields from outgoing serialized JSON payloads |
Option<T> | Field Type | Standard Rust wrapper for nullable or optional JSON fields, eliminating null pointer exceptions |
JSON to Rust Type Inference Matrix
| JSON Data Type | Sample JSON Value | Inferred Rust Type | Architectural Context / Best Practice |
|---|---|---|---|
| String | "John Doe" | String | Owned, heap-allocated UTF-8 string |
| Integer (Standard) | 42 | i64 (or i32) | Default 64-bit signed integer; safely accommodates database IDs |
| Unsigned Integer | 100 | u64 | Used for non-negative counters and timestamp milliseconds |
| Float / Real Number | 99.95 | f64 | Double-precision IEEE 754 floating-point number |
| Boolean | true / false | bool | Native boolean primitive |
| Nullable Value | null | Option<T> | Represents absence of a value without runtime null crashes |
| Array of Primitives | ["admin", "user"] | Vec<String> | Growable, heap-allocated vector |
| Array of Objects | [{"sku": "A1"}, ...] | Vec<Item> | Vector of nested child structs |
| Nested Object | {"geo": {"lat": 30.2}} | Geo (Sub-struct) | Recursively generates independent child struct |
| Arbitrary JSON | {"meta": {...}} | serde_json::Value | Fallback for unconstrained, dynamic JSON sub-trees |
Step-by-Step Practical Transformation Example
Let us examine how an enterprise SaaS subscription JSON payload is translated into clean, idiomatic Rust source code:
Raw Input JSON:
{
"subscription_id": "sub_882910",
"plan_name": "Enterprise Pro",
"monthly_price": 299.50,
"is_active": true,
"cancellation_reason": null,
"customer": {
"account_id": 4021,
"company_name": "Acme Industrial"
},
"features": ["audit_logs", "sso_saml", "custom_domains"]
}
Production-Ready Rust Source Code with Serde:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Customer {
pub account_id: i64,
pub company_name: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Subscription {
pub subscription_id: String,
pub plan_name: String,
pub monthly_price: f64,
pub is_active: bool,
pub cancellation_reason: Option<String>,
pub customer: Customer,
pub features: Vec<String>,
}
// Verification Example using serde_json:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let json_data = r#"
{
"subscription_id": "sub_882910",
"plan_name": "Enterprise Pro",
"monthly_price": 299.50,
"is_active": true,
"cancellation_reason": null,
"customer": {
"account_id": 4021,
"company_name": "Acme Industrial"
},
"features": ["audit_logs", "sso_saml", "custom_domains"]
}
"#;
// Zero-overhead deserialization:
let sub: Subscription = serde_json::from_str(json_data)?;
println!("Loaded subscription for {}", sub.customer.company_name);
assert_eq!(sub.is_active, true);
// Serialization back to JSON:
let serialized = serde_json::to_string_pretty(&sub)?;
println!("Serialized JSON:\n{}", serialized);
Ok(())
}
Comparison Matrix: Serialization Across Compiled Systems
| Metric / Feature | Rust (Serde) | Go (encoding/json) | C# (System.Text.Json) | C++ (nlohmann/json) |
|---|---|---|---|---|
| Memory Safety | 100% Compile-Time Guaranteed | Garbage-collected pointer safety | Garbage-collected | Manual memory management |
| Null Safety | Option<T> (Zero null errors) | Nil pointers can trigger panics | Nullable reference types | nullptr risks |
| Execution Speed | Fastest (Ahead-of-Time Monomorphization) | Fast | Very Fast | Fast |
| Reflection Cost | Zero (Compile-time code generation) | Uses runtime reflection (reflect) | Fast (Source Generators) | Template metaprogramming |
| Naming Conventions | snake_case (Automated mapping) | PascalCase exported fields | PascalCase properties | Flexible |
Critical Edge Cases & Common Rust Traps
1. The Eq and Hash Derivation Trap on Floating-Point Fields
In Rust, the IEEE 754 floating-point types (f32 and f64) do not implement the standard Eq or Hash traits because NaN != NaN under floating-point rules.
- If you attempt to write
#[derive(Debug, PartialEq, Eq, Hash)]on a struct containingpub price: f64, the Rust compiler terminates with:the trait 'Eq' is not implemented for 'f64' - Remediation: Only derive
PartialEqon structs containing floating-point numbers. If hashing is strictly required (forHashSetorHashMapkeys), wrap the float in an ordered-float crate (ordered_float::OrderedFloat<f64>).
2. Rust Reserved Keyword Name Collisions (type, match, ref)
JSON payloads frequently feature keys that collide with Rust reserved language keywords (such as type, ref, fn, struct, or move).
- Solution: Use Rust's raw identifier syntax (
r#type) or explicit Serde field renaming:#[serde(rename = "type")] pub kind: String,
3. Missing Fields vs Null Fields in JSON APIs
In REST APIs, there is a subtle difference between a field being explicitly set to null ("notes": null) versus being omitted entirely ({}).
- In Rust, both evaluate to
Nonewhen typed asOption<T>. - If an API payload omits a field that is not wrapped in
Option<T>, Serde throwsmissing field 'field_name'. - Best Practice: For APIs where fields may be omitted, combine
Option<T>with#[serde(default)].