How to Generate Rust Structs from JSON
Deserializing JSON in Rust means defining structs that derive Serialize and Deserialize. Generating them from a sample gets the field names, attributes, and types right automatically. Here's how the output is built.
From JSON to structs
Each JSON object becomes a struct, nested objects become their own structs, and every struct derives serde's traits:
{ "id": 1, "user_name": "Ada" }
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
pub id: i64,
pub user_name: String,
}
The #[derive(Serialize, Deserialize)] is what lets serde_json turn the struct back into your exact JSON and parse it again.
Field names and serde rename
Rust convention is snake_case field names. Most JSON keys already match, but when a key uses a different style — userName, first-name — the field is snake-cased and a #[serde(rename = "...")] attribute preserves the original key:
#[serde(rename = "userName")]
pub user_name: String,
Keys that collide with Rust keywords become raw identifiers like r#type, so they stay valid without changing the wire format.
Optional fields and unknown types
When you convert an array of objects and a key is missing from some elements, the field becomes an Option<T> so it can be None:
pub views: Option<i64>,
Arrays map to Vec<T>, whole numbers become i64 and decimals f64, and a null or a field with no inferable type falls back to serde_json::Value.
Related
Generating types for another language? See JSON to Go and JSON to Kotlin.
Try it
Paste a JSON response and get Rust structs instantly — everything runs in your browser, nothing uploaded.