Sheet 04 Serde structs
JSON to Rust
Paste JSON samples and get Rust structs that derive Serialize and Deserialize, with snake_case fields mapped back to your keys.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Root {
pub service: String,
pub version: String,
pub port: i64,
pub debug: bool,
pub limits: Limits,
pub replicas: Vec<Replica>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Limits {
pub rps: i64,
pub burst: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Replica {
pub region: String,
pub weight: f64,
pub timeout: Timeout,
#[serde(skip_serializing_if = "Option::is_none")]
pub canary: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Timeout {
Integer(i64),
String(String),
}
1 sample · 3 types
How it works
Fields are snake_case. For each struct the generator picks the rename_all rule that matches the most keys (camelCase, kebab-case and so on) and adds #[serde(rename = "...")] only where a key still differs. Keywords become raw identifiers such as r#type.
- Option<T>
- Keys missing from some objects and values that can be null become
Option. With "Skip None", keys that were missing are left out again when serializing, so the output matches the input. - Mixed values
- A value that is sometimes a number and sometimes a string becomes an
#[serde(untagged)]enum with one variant per kind. Values of unknown type areserde_json::Value. - Derives
SerializeandDeserializeare always derived. WithDefault, untagged enums get a smallimpl Default, since an enum with data cannot derive it.
Questions
Which crates does the code need?
serde with the derive feature and serde_json: add serde = { version = "1", features = ["derive"] } and serde_json = "1" to Cargo.toml, then parse with serde_json::from_str::<Root>(text).
Why i64 and f64?
JSON numbers have no size, so integers become i64 (u64 when larger positive values appear) and anything with a fraction or exponent becomes f64.
Is my JSON uploaded?
No. The code is generated by JavaScript running in this tab, and nothing you paste leaves it. The site counts page views with Cloudflare Web Analytics, which sets no cookies and never receives what you paste.