JSON to Rust Struct

Generate Rust structs with Serde derive macros from JSON data. Produces idiomatic snake_case fields with proper type mapping and serde rename attributes.

Input JSON
Rust Struct Output

Features

đŸĻ€ Idiomatic Rust

  • snake_case field names
  • Serde derive macros
  • pub struct and pub fields
  • Nested struct generation

đŸ“Ļ Serde Integration

  • #[derive(Serialize, Deserialize)]
  • #[serde(rename)] for camelCase keys
  • Option<T> for nullable fields
  • Vec<T> for arrays

âš™ī¸ Configurable Output

  • Selectable integer types
  • Optional Clone derive
  • Configurable pub visibility
  • All-nullable option

Rust Serde Guide

Serde Derive Macros

Serde is Rust's serialization framework. Add it to your Cargo.toml and use derive macros for zero-cost JSON serialization.

# Cargo.toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct User {
    pub id: i64,
    pub name: String,
    #[serde(rename = "isActive")]
    pub is_active: bool,
}

Tips for Serde structs in real projects

Serde makes JSON handling in Rust fast and type safe. Because Rust has no implicit nulls or loose numbers, it pays to review generated structs for optional fields and number sizes before relying on them.

Tips and common pitfalls

  • Add #[serde(default)] to fields that may be missing so decoding falls back to the default value instead of failing.
  • Use #[serde(rename_all = "camelCase")] on the struct instead of renaming every field individually.
  • Choose u64 or i64 for IDs, and f64 only for true decimals. Money is safer as an integer number of cents.
  • For unknown or dynamic sections, use serde_json::Value and parse that part later.

More questions

How do I keep fields I did not model?

Add a field #[serde(flatten)] extra: HashMap<String, Value> to collect every unknown key. It is handy for proxies that must pass data through unchanged.

Why do I get "invalid type: null, expected a string"?

The JSON contains null for a field typed as String. Change it to Option<String>.