How to use it
- Paste a JSON sample. Arrays with several objects give the best result.
- Choose whether structs and fields are pub and whether None values are skipped when serializing.
- Copy the code into your crate and parse with
let root: Root = serde_json::from_str(&text)?;.
How it works
The sample is read into a shape: every key with every type seen at that place. All objects of one array are merged into one struct, so a key present in only some of them becomes Option
- Each struct derives Debug, Clone, Serialize and Deserialize.
- Struct names come from keys: items holds Vec
- , customer becomes Customer.
- A top-level array gives a type alias, such as pub type Root = Vec
;.
Worked example
{"items":[{"sku":"A","note":null,"qty":1},{"sku":"B","note":"x"}]} without pub and with Skip None gives:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Root {
items: Vec<Item>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Item {
sku: String,
#[serde(skip_serializing_if = "Option::is_none")]
note: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
qty: Option<i64>,
}
Tips
- If every key is camelCase, you can replace the per-field renames with one #[serde(rename_all = “camelCase”)] on the struct.
- Narrow types where you know the range: u32 for counts, u8 for small codes.
- Add #[serde(deny_unknown_fields)] if extra keys should be an error.