How to Generate Rust Structs from JSON

By Ramanathan Aug 25, 2026 1 min read JSON to Rust

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.

About the author

Ramanathan · Software Engineer & Solutions Architect

I'm a Software Engineer and Solutions Architect with 20+ years of experience building enterprise applications across BFSI, Healthcare, Retail, Manufacturing, and Industrial Automation. I've spent those two decades living in JSON, tokens, regexes, and config files — so I built the fast, private, no-login developer tools I always wanted to reach for myself.

Last updated: Aug 25, 2026