Sub topic 2
Round-tripping JSON with `serde_json`
This chapter assumes Rust structs, enums, traits, generics, lifetimes, Cargo, Result, and JSON. Serde provides the conversion rules; serde_json applies them to JSON text.
Serialize and deserialize values
Add Serde with its derive macros and JSON support:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Serialize converts a Rust value into a format. Deserialize converts a format into a Rust value.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
let user = User {
id: 1,
name: "Ada".into(),
email: None,
};
let json = serde_json::to_string(&user)?;
println!("{json}");
let restored: User = serde_json::from_str(&json)?;
println!("{restored:?}");
Ok(())
}The ? operator returns a serde_json::Error if conversion fails. Serialization produces null for None.
Shape fields with attributes
Attributes adjust the derived behavior without requiring a manual implementation:
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Config {
user_name: String,
#[serde(default)]
retry_count: u32,
#[serde(skip_serializing_if = "Option::is_none")]
proxy_url: Option<String>,
}rename_all changes Rust names such as user_name to userName. default supplies 0 when retryCount is absent. skip_serializing_if omits proxyUrl when it is None. deny_unknown_fields rejects unexpected JSON keys.
Choose an enum representation
Enum representation determines the JSON shape:
| Representation | Example shape | Typical use |
|---|---|---|
| External tag | `{"Click":{"x":1,"y":2}}` | Default, unambiguous variants |
| Internal tag | `{"type":"click","x":1,"y":2}` | Object-based APIs |
| Adjacent tags | `{"type":"click","data":{"x":1,"y":2}}` | Separate tag and payload |
| Untagged | `{"x":1,"y":2}` | Existing shape without a tag |
For an internal tag:
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Event {
Click { x: i32, y: i32 },
Quit,
}The Click value becomes {"type":"click","x":1,"y":2}. Choose the representation required by the external JSON contract, not merely the shortest syntax.
Exercise
Which attribute rejects a JSON object containing a key that is not declared in the struct?
Show answer
#[serde(deny_unknown_fields)].