Basic Rust Struct from Flat JSON
Convert a flat JSON object into a Rust struct with #[derive(Serialize, Deserialize)] and snake_case field names. The starting point for every serde project.
Basics
Detailed Explanation
Generating a Rust Struct from Flat JSON
When the JSON has no nested objects or arrays, the output is a single struct whose fields map one-to-one onto the keys.
Example JSON
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"active": true
}
Generated Rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Root {
pub id: i32,
pub name: String,
pub email: String,
pub active: bool,
}
What the converter decided
idis a whole number and fits in 32 bits, so it becamei32. If the value were larger than2_147_483_647the converter would picki64instead.nameandemailare JSON strings, so they map to Rust's ownedString. If you need to deserialize without owning the data, you can change those to&strand supply a borrowed lifetime — but that is rarely worth the friction.activeis a JSON boolean, mapped directly tobool.- The struct is wrapped in a derive line that adds
DebugandClone(handy during development) plus the two serde macros that makeserde_json::from_strandserde_json::to_stringwork without any boilerplate.
Using the struct
let json = r#"{ "id": 42, "name": "Alice", ... }"#;
let user: Root = serde_json::from_str(json)?;
If you prefer a more domain-specific name, change the Root struct input from Root to User. The converter regenerates the output instantly.
Use Case
Almost every CLI tool, script, or backend service that reads a JSON config file or hits a REST endpoint starts with this exact pattern. It is the smallest useful unit of serde struct generation.