JSON 转 Rust 结构体
将 JSON 转换为带 serde 注解的 Rust struct,自动处理嵌套对象、数组及所有 Rust 类型。
What Is the JSON to Rust Struct Generator?
The JSON to Rust struct generator converts a JSON object into Rust struct definitions annotated with #[derive(Debug, Clone, Serialize, Deserialize)]. Paste any JSON and the tool produces ready-to-use Rust code with proper type mappings, nested struct extraction, and #[serde(rename)] attributes where field names differ from their snake_case equivalents.
This tool is useful when building Rust REST clients, mapping API responses to typed data structures, or scaffolding models from JSON schemas. It handles the repetitive struct definition work so you can focus on business logic.
How to Use the JSON to Rust Generator
- Paste your JSON object into the left panel, or click Load Sample.
- Set the root struct name (defaults to Root).
- The generated Rust structs appear on the right with serde imports and derive macros.
- Click Copy to copy all struct definitions.
- Add
serde = { features = ["derive"] }andserde_jsonto yourCargo.toml.
Features
- Generates structs with #[derive(Debug, Clone, Serialize, Deserialize)]
- Adds
use serde::{{Deserialize, Serialize}}import automatically - Handles nested objects — each becomes a separate named struct
- Maps JSON arrays to Vec<T> with inferred element type
- Type mapping: string → String, boolean → bool, integer → i64, decimal → f64, null → Option<Value>
- Field names automatically converted to snake_case with #[serde(rename)] when needed
- Struct names automatically converted to PascalCase
- Configurable root struct name
FAQ
What is serde in Rust?
Serde is a Rust framework for serializing and deserializing data structures. It is the standard way to convert between Rust structs and data formats like JSON, TOML, YAML, and others. The serde and serde_json crates are used in nearly every Rust project that handles JSON data.
How are JSON types mapped to Rust types?
JSON strings → String, booleans → bool, integers → i64, floats → f64, arrays → Vec<T>, objects → named struct, null → Option<serde_json::Value>.
Why does the generator add #[serde(rename)] attributes?
Rust uses snake_case for field names by convention, but JSON APIs often use camelCase or other conventions. When a JSON key does not match its snake_case equivalent, the generator adds #[serde(rename = "originalKey")] so serde correctly maps the JSON field to the Rust struct field during deserialization.
How are nested JSON objects handled?
Each nested JSON object generates a separate Rust struct. The struct name is derived from the JSON key using PascalCase. For example, a key address containing an object generates an Address struct, and the parent struct has a field of type Address.