How to use the JSON to Rust
- Paste a JSON sample.
- Set the root struct name.
- Review integer widths and Option fields; tighten them to what the API guarantees.
- Copy the structs into your crate with serde = { version = "1", features = ["derive"] } and serde_json in Cargo.toml.
Worked example
A user with a nickname that may be null
Input
{"id":5,"name":"Ada","is_admin":false,"tags":["x"],"nickname":null}Rust
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
pub id: i64,
pub name: String,
pub is_admin: bool,
pub tags: Vec<String>,
pub nickname: serde_json::Value,
}nickname is null in the sample, so its inner type is unknown; replace serde_json::Value with String if that is what it holds.
serde attributes you will likely add
| Attribute | Where | Effect |
|---|---|---|
| #[serde(rename_all = "camelCase")] | struct | Maps userId in JSON to user_id in Rust |
| #[serde(rename = "type")] | field | Use a JSON key that is a Rust keyword |
| #[serde(default)] | field or struct | Missing key gets Default::default() |
| #[serde(skip_serializing_if = "Option::is_none")] | field | Omit None when writing JSON |
| #[serde(deny_unknown_fields)] | struct | Error on keys not in the struct |
Option<T>, missing keys and null
With serde's derive, an Option<T> field accepts both a missing key and an explicit null and yields None in either case. Any other field type makes a missing key an error unless you add #[serde(default)]. That makes Option the right choice for anything the API may leave out.
Keywords and integer sizes
Keys like "type", "match" or "ref" are Rust keywords. Name the field r#type or ty and add #[serde(rename = "type")]. Integers default to i64, which covers every JSON integer that JavaScript can represent exactly; use u64 for unsigned IDs above i64::MAX, or u32/u8 when you know the range is small.
JSON to Rust FAQ
How do I parse JSON into a struct in Rust?
Derive Deserialize on the struct and call serde_json::from_str::<Root>(&text)?, or from_slice for bytes and from_reader for files. Errors include the line and column.
How do I handle camelCase JSON keys in Rust?
Put #[serde(rename_all = "camelCase")] on the struct and keep snake_case field names. serde converts between the two in both directions.
What is serde_json::Value for?
It is a dynamically typed JSON value. Use it for fields whose shape varies or is unknown, then match on it or convert it later with serde_json::from_value.
Does serde ignore unknown JSON fields?
Yes by default. Add #[serde(deny_unknown_fields)] to the struct to turn them into errors.
Why do I get "missing field" errors from serde?
A non-Option field's key was absent from the input. Make it Option<T> or add #[serde(default)] so serde fills in the default value.

