Skip to content

JSON to Rust Struct Generator - Serde Converter

Input JSON
Rust Output

Typed serde structs, not serde_json::Value

You can read any JSON into serde_json::Value and index it with v["steps"][0]["name"], but you give up the compiler checks. This tool writes #[derive(Serialize, Deserialize)] structs for a sample payload. Fields are snake_case, and #[serde(rename)] is only added where the Rust name and the JSON key differ.

Example: a CI deployment event

Input, with the root type name set to Deployment:

{
  "type": "deployment",
  "repoName": "devutil",
  "durationMs": 48211,
  "commit": { "sha": "9f1c2ab", "message": "bump deps" },
  "steps": [
    { "name": "build", "ok": true },
    { "name": "test", "ok": false, "exitCode": 1 }
  ],
  "meta": {}
}

Output:

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Deployment {
    pub r#type: String,
    #[serde(rename = "repoName")]
    pub repo_name: String,
    #[serde(rename = "durationMs")]
    pub duration_ms: i64,
    pub commit: Commit,
    pub steps: Vec<Step>,
    pub meta: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Step {
    pub name: String,
    pub ok: bool,
    #[serde(rename = "exitCode")]
    pub exit_code: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Commit {
    pub sha: String,
    pub message: String,
}

type is a keyword, so the field is the raw identifier r#type. Serde strips the r# when it matches keys, so no rename is needed. self, super and crate can't be raw identifiers and get a trailing underscore plus a rename instead. exitCode was only on the failed step, so it is Option<i64>. meta was an empty object, so there is nothing to build a struct from and it becomes a HashMap<String, serde_json::Value>.

Edits worth making

type with a fixed set of values is a good fit for an enum. If the payload shape depends on it, #[serde(tag = "type")] on an enum of variants handles that, but it needs samples of each variant and you'll have to write it by hand. Timestamps arrive as String; with the chrono crate's serde feature you can change them to DateTime<Utc>. Add #[serde(deny_unknown_fields)] to a struct if an unexpected key should be an error instead of being ignored.

Values that change type between records, and fields that were only ever null, become serde_json::Value. That compiles and parses anything, so look for it in the output and replace it where you know the real type. An untagged enum (#[serde(untagged)]) is the usual replacement for a field that is sometimes a number and sometimes a string.

For a schema that other services can validate against, see JSON to JSON Schema.

Same JSON, other languages

Every generator here reads the sample the same way, so a key that is optional or nullable in one language is optional or nullable in the others. Paste the same input into: TypeScript, Zod, Go, Python, Java, C#, JSON Schema.

Related Tools

Frequently Asked Questions

Which crates do I need?
`serde` with the derive feature and `serde_json`. In Cargo.toml: `serde = { version = "1", features = ["derive"] }` and `serde_json = "1"`. Then `let d: Deployment = serde_json::from_str(&text)?;`.
Why per-field rename instead of #[serde(rename_all = "camelCase")]?
Real payloads mix styles, and a single `rename_all` breaks on the first key that doesn't follow it. Per-field `rename` is explicit and only appears where the Rust name differs. If every key in a struct is camelCase, deleting the renames and adding `rename_all = "camelCase"` gives the same result.
Does a missing key fail deserialization?
Not for `Option` fields. Serde's derive treats a missing `Option<T>` field as `None`. A missing non-Option field is an error, which is why keys absent from some samples are wrapped in `Option`. For other types, `#[serde(default)]` uses `Default::default()` instead.
None serializes as null. How do I leave the key out?
Add `#[serde(skip_serializing_if = "Option::is_none")]` to the field. The generator doesn't add it because it changes the output format, and some APIs treat a missing key and null differently.
Why i64 and f64?
They hold any integer or decimal a typical JSON API sends. Narrow to `u32` or `u8` where you know the range; serde returns an error rather than truncating if a value doesn't fit. Values above `i64::MAX` need `u64`.