JSON to Rust Struct Converter

Generate Rust structs that derive serde's Serialize and Deserialize from a JSON sample.

Generate serde structs from JSON

In Rust, the usual way to read JSON is to deserialize it into structs with serde and serde_json. This converter writes those structs from a sample: each object becomes a struct with #[derive(Serialize, Deserialize)], nested objects get their own struct, arrays become Vec<T>, whole numbers become i64, decimals f64 and strings String. Field names are kept in snake_case, and a #[serde(rename = "...")] attribute is added when a JSON key is not a valid snake_case identifier.

How to use

  1. Paste a JSON sample, such as an event payload or a config file.
  2. Enter the root struct name, for example Event.
  3. Add serde (with the derive feature) and serde_json to Cargo.toml, paste the structs into a module, and parse with serde_json::from_str::<Event>(&text).

Frequently asked questions

Why are the fields private?
The generator leaves fields without pub, which is enough for serde inside the module. Add pub to the fields you need to read from other modules.
How are optional fields represented?
If a field is null or missing in some of the sample items, it is generated as Option<T>, so serde accepts both cases. Fields that are always present get plain types, and a missing one is a deserialization error.
Which crates do I need?
Add serde with features = ["derive"] and serde_json. The comment at the top of the output also shows the older extern crate style, which current Rust editions do not need.

Example: JSON to Rust

Input JSON

{
  "event_type": "page_view",
  "timestamp": 1735689600,
  "user_id": "u_123",
  "properties": { "path": "/pricing", "referrer": "google" }
}

Generated Rust (Event)

// Example code that deserializes and serializes the model.
// extern crate serde;
// #[macro_use]
// extern crate serde_derive;
// extern crate serde_json;
//
// use generated_module::Event;
//
// fn main() {
//     let json = r#"{"answer": 42}"#;
//     let model: Event = serde_json::from_str(&json).unwrap();
// }

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Event {
    event_type: String,

    timestamp: i64,

    user_id: String,

    properties: Properties,
}

#[derive(Serialize, Deserialize)]
pub struct Properties {
    path: String,

    referrer: String,
}

Convert JSON to other languages